I need to create an array like this
["January 2020, February 2020, March 2020, April 2020, May 2020, June 2020, and so on till last month]
With Date::MONTHNAMES, it enumerizes only the months but I don't find a way to add the years.
Thank you,
You can use map method.
month_names = Date::MONTHNAMES.compact.map{ |m| "#{m} #{Time.zone.now.year}" }
p month_names
#=> ["January 2021", "February 2021", "March 2021", "April 2021",
"May 2021", "June 2021", "July 2021", "August 2021", "September 2021",
"October 2021", "November 2021", "December 2021"]
You can simply map it and add the current year, something like this Date::MONTHNAMES.compact.map{ |month| "#{month} #{Date.current.year}" }
I would go with:
def month_names(year)
1.upto(12).map |month|
Date.new(year, month).strftime("%b %Y")
end
end
While this seems like overkill compared to simple string concatention you can easily swap out strftime for the I18n module to localize it.
def month_names(year)
1.upto(12).map |month|
I18n.localize(Date.new(year, month), format: :long)
end
end
# config/locale/pirate.yml
pirate:
date:
formats:
long: "Aargh! it be the on the fair month of %m %Y"
Related
I have issue in custom ordering data.
Here is example
I would like to be sorted first by year and than by week
I want 1 2022 to be at the and of the line.
I have tried adding few things.
Is there a way to sort this out by adding new table with weekYear column and some sortOrder column
which I have to populate with custom values as well?
I prefer solution to be dynamic..
If you have any solution please advice!
I suggest
Create a table from your column names
Split the column by space delimiter
Change column types to number
sort by Year and then by Week
Change column types to text
combine the columns with space delimiter
use this new, sorted list to re-order the original columns
I did this as a custom function:
(tbl as table, optional colsToSort as list) =>
let
colHdrs = if colsToSort=null then Table.ColumnNames(tbl) else colsToSort,
hdrCol = Table.FromList(colHdrs,Splitter.SplitTextByDelimiter(" ")),
//type as number for sorting
typeAsNumber = Table.TransformColumnTypes(hdrCol,{{"Column1", Int64.Type},{"Column2",Int64.Type}}),
sorted = Table.Sort(typeAsNumber,{{"Column2", Order.Ascending}, {"Column1", Order.Ascending}}),
//type as text to combine
typeAsText = Table.TransformColumnTypes(sorted,{{"Column1", Text.Type}, {"Column2", Text.Type}}),
combine = Table.CombineColumns(typeAsText,{"Column1","Column2"},Combiner.CombineTextByDelimiter(" "),"orderHeaders"),
//re-Order the column headers in the original table
newOrder = Table.ReorderColumns(tbl,combine[orderHeaders])
in
newOrder
And you could call it from your original query as:
let
Source = Excel.CurrentWorkbook(){[Name="Table13"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{
{"41 2021", Int64.Type}, {"42 2021", Int64.Type}, {"43 2021", Int64.Type},
{"46 2021", Int64.Type}, {"1 2022", Int64.Type}, {"48 2021", Int64.Type},
{"50 2021", Int64.Type}, {"49 2021", Int64.Type}, {"51 2021", Int64.Type},
{"52 2021", Int64.Type}}),
//custom function here
sortHdrs = fnSortHeaders(#"Changed Type")
in
sortHdrs
If ALL of your columns are in the format of weeknumber year so that you want to sort ALL of them, it may be simpler to do this without a separate function. The advantage of the separate function is that you can more easily remove the column names you don't want to include in the sort
Here is code that will sort the column headers with no need of a separate function. It uses the same algorithm as above
let
Source = Excel.CurrentWorkbook(){[Name="Table13"]}[Content],
#"Changed Type2" = Table.TransformColumnTypes(Source,{
{"41 2021", Int64.Type}, {"42 2021", Int64.Type}, {"43 2021", Int64.Type},
{"46 2021", Int64.Type}, {"1 2022", Int64.Type}, {"48 2021", Int64.Type},
{"50 2021", Int64.Type}, {"49 2021", Int64.Type}, {"51 2021", Int64.Type},
{"52 2021", Int64.Type}}),
//create header list
//this assumes ALL column headers are to be sorted, but you can make partial lists for the column sorting
hdrs = List.Combine(List.Transform(Table.ColumnNames(#"Changed Type2"), each Text.Split(_," "))),
//split into month and year and put into a table
monthYear = Table.FromColumns({List.Alternate(hdrs,1,1,1),List.Alternate(hdrs,1,1,0)},{"Month","Year"}),
//change data type to number and sort by Year and then Month
#"Changed Type" = Table.TransformColumnTypes(monthYear,{{"Month", Int64.Type}, {"Year", Int64.Type}}),
#"Sorted Rows" = Table.Sort(#"Changed Type",{{"Year", Order.Ascending}, {"Month", Order.Ascending}}),
//change data type to text and join with space delimiter
#"Changed Type1" = Table.TransformColumnTypes(#"Sorted Rows",{{"Month", type text}, {"Year", type text}}),
sortedHeaders = Table.CombineColumns(#"Changed Type1",{"Month", "Year"},
Combiner.CombineTextByDelimiter(" ", QuoteStyle.None),"newOrder")[newOrder],
//reOrder the original table
sortedTableColumns= Table.ReorderColumns(#"Changed Type2",sortedHeaders)
in
sortedTableColumns
have a nice day everyone, i want to ask something, i need to make JSON array using square bracket instead of curly breacket, but now i've JSON like this:
{
noTransaksi: "202006041323372",
nopolTransaksi: "B11",
nominalTransaksi: "1.000",
masukTransaksi: "04 June 2020 13:23:37",
keluarTransaksi: "04 June 2020 14:26:25",
lokasiTransaksi: "Jakarta",
nipKaryawan: "002002",
shiftTransaksi: "1"
},
{
noTransaksi: "202006040703302",
nopolTransaksi: "B2213",
nominalTransaksi: "0",
masukTransaksi: "04 June 2020 07:03:30",
keluarTransaksi: "04 June 2020 14:25:42",
lokasiTransaksi: "Jakarta",
nipKaryawan: "002007",
shiftTransaksi: "1"
},//...
i want to change it to something like this:
[
noTransaksi: "202006041323372",
nopolTransaksi: "3752",
nominalTransaksi: "1.000",
masukTransaksi: "04 June 2020 13:23:37",
keluarTransaksi: "04 June 2020 14:26:25",
lokasiTransaksi: "RSUDTA",
nipKaryawan: "002002",
shiftTransaksi: "1"
],
[
noTransaksi: "202006040703302",
nopolTransaksi: "AG1592",
nominalTransaksi: "0",
masukTransaksi: "04 June 2020 07:03:30",
keluarTransaksi: "04 June 2020 14:25:42",
lokasiTransaksi: "RSUDTA",
nipKaryawan: "002007",
shiftTransaksi: "1"
],//....
so i can fit the JSON to my datatable, because it need square bracket instead of curly bracket, anyway i'm using reactjs too, it is possible to make JSON array like that?
oh ya, this is my code
if(mysqli_num_rows($result) > 0){
$emparray = array();
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = array(
'noTransaksi'=>$row['noTransaksi'],
'nopolTransaksi'=>strtoupper($row['nopolTransaksi']),
'nominalTransaksi'=>number_format($row['nominalTransaksi'],0,",","."),
'masukTransaksi'=>date("d F Y H:i:s", strtotime($row['masukTransaksi'])),
'keluarTransaksi'=>date("d F Y H:i:s", strtotime($row['keluarTransaksi'])),
'lokasiTransaksi'=>strtoupper($row['lokasiTransaksi']),
'nipKaryawan'=>strtoupper($row['nipKaryawan']),
'shiftTransaksi'=>$row['shiftTransaksi'],
);
}
$no++;
}
echo json_encode($emparray);
}
mysqli_close($con);
i really appriciate if somebody can help me:)
The square brackets produce a list/array.
The curly brackets produce an object with key/value pairs.
The list can then be a value of a key/value pair.
you cant just change it u can use [] inside the {} brackets
Beginner with ReactJS, I use now the wonderful ReactJS Datepicker. Questions about my custom date format :
i found no doc to explain all the possibilities like M is month, MM is month on 2 letters, etc. (shall I look to the github code? which source?)
How to add the name of the day... like Saturday. I tried dddd but it shows the number of the day with 2 leading 0 before !!
How to exclude the non office hour (like hours 0 to 8 and 20 to 23), I tried the excludesTimes below but no way.
Here is my code :
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
locale={fr}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={60}
dateFormat="dddd, DDD, ddd, d, dd MMMM yyyy à HH'h'mm"
timeCaption="Heure"
minDate={new Date()}
showDisabledMonthNavigation
placeholderText="Choisir ici ..."
excludeTimes={[0, 1, 2, 3, 4]}
/>
Date shown in input field is then :
0023, 082, 023, 23, 23 mars 2019 à 20h00
Thanks
React datepicker uses Moment.js for dates, I think you should review the docs at his website.
For example MMMM Do YYYY, h:mm:ss a should return a date formated as March 21st 2019, 8:50:37 am.
EDIT
I went to the repo and it appears the author removed moment from package, so I gave a try to the formatting dates guide found here and it appears to be working now! Per example use "eeee" if you want day of the week.
I made a working example at codesandbox.
You also can convert manually ...
const convertDate = str => {
str = str.toString();
let parts = str.split(" ");
let months = {
Jan: "01",
Feb: "02",
Mar: "03",
Apr: "04",
May: "05",
Jun: "06",
Jul: "07",
Aug: "08",
Sep: "09",
Oct: "10",
Nov: "11",
Dec: "12"
};
return parts[3] + "-" + months[parts[1]] + "-" + parts[2];
};
:) Reinventing the wheel
I have the following code for new Date() along with a function that formats the new Date() to something a bit more digestible:
data.onbCase.push({
first_name: onbCase.getDisplayValue('subject_person.first_name'),
last_name: onbCase.getDisplayValue('subject_person.last_name'),
start_date: formatDate(new Date(onbCase.getDisplayValue('hr_profile.employment_start_date')))
});
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate(),
monthIndex = date.getMonth(),
year = date.getFullYear();
return new Date(monthNames[monthIndex].substr(0,3) + ' ' + day + ', ' + year);
}
<td ng-show="c.options.start_date" title="{{item.start_date}}">{{item.start_date | date:'mediumDate'}}</td>
However, this always returns a date that is one day behind the correct date. Can someone explain why this happens and how to fix it? I know I can simply add 1 to the getDate():
var day = date.getDate() +1;
This seems incorrect though...any advice?
For more information see this question: Is the Javascript date object always one day off?
The new Date() string parser is not reliable, because you get different results for different string date formats.
new Date()
// Fri Feb 15 2019 15:08:14 GMT-0600 (Central Standard Time)
new Date("2019-02-15")
// Thu Feb 14 2019 18:00:00 GMT-0600 (Central Standard Time)
new Date("2019-02-15 00:00:00")
// Thu Feb 15 2019 18:00:00 GMT-0600 (Central Standard Time)
new Date("02/15/2019")
// Fri Feb 15 2019 00:00:00 GMT-0600 (Central Standard Time)
Some date formats, especially if you don't include time information, will treat your date as originating in Greenwich Mean Time and then offset your date by your computer's locale. This will result in the date being offset by negative 6 hours(CST) effectively altering your day to the day before.
I have a text file which looks like this
{
"TYPE": "EMAIL",
"ITEMS": [
{
"SENT": "2016-02-01T19:03:02.00Z",
"SUBJECT": "UPCOMING EVENTS: ORIENTATION 2016",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "WE'RE PLEASED TO BE WORKING WITH RMIT LINK'S ORIENTATION TEAM AND RUSU TO WELCOME ALL NEW STUDENTS TO CAMPUS THROUGH A SERIES OF EXCITING ORIENTATION EVENTS. THIS EMAIL SERVES AS A NOTIFICATION TO MAKE SURE YOU KNOW WHEN THE MAJOR EVENTS ARE OCCURRING, TO ENSURE THEY DON'T INTERRUPT YOUR WORK AND SO THAT YOU ARE ABLE TO ENCOURAGE ALL NEW STUDENTS TO ATTEND. BRUNSWICK ALL STUDENTS WELCOME, 23 FEBRUARY 12 - 1:30PM BRUNSWICK COURTYARD. BUNDOORA ALL STUDENTS WELCOME, 24 FEBRUARY 12 - 2PM BUNDOORA WEST CONCOURSE. CITY ALL STUDENTS WELCOME, 25 FEBRUARY 11AM - 2:30PM ALUMNI COURTYARD, UNIVERSITY WAY. RUSU WELCOME BASH, 25 FEBRUARY 4PM - 9PM ALUMNI COURTYARD. CITY CLUBS DAY, 3 MARCH 11AM - 2PM ALUMNI COURTYARD, UNIVERSITY WAY."
},
{
"SENT": "2016-03-03T19:03:02.00Z",
"SUBJECT": "PROJECT 1 FIRST TIME MEETING",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "EARLY NEXT WEEK IS GOOD FOR US. HOW ABOUT MONDAY 11AM?"
},
{
"SENT": "2016-03-03T19:03:02.00Z",
"SUBJECT": "PROJECT 1 FIRST TIME MEETING",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "EARLY NEXT WEEK IS GOOD FOR US. HOW ABOUT TUESDAY 11:30 AM?"
},
}
I'm trying to extract the information making ITEMS as an array of Hashes. So that i can access the values for sent subject timezone and etc.
I have tried this it doesnt work. Any help?
my #AoH ;
while ( <> ) {
my $rec = {};
for my $field ( split ) {
(my $key, my $value) = split /:/, $field;
$rec->{$key} = $value;
}
push #AoH, $rec;
}
That's JSON data (JavaScript Object Notation) except that the very last comma , should be a closing square bracket ]. Use the JSON module to decode it into a Perl data structure
This program shows the principle. It prints just the subject line of each item, but I think you get the idea
use strict;
use warnings 'all';
use JSON qw/ decode_json /;
my $json = do {
open my $fh, '<:raw', 'text_file.txt' or die $!;
local $/;
<$fh>;
};
my $data = decode_json($json);
my $items = $data->{ITEMS};
for my $item ( #$items ) {
print $item->{SUBJECT}, "\n";
}
output
UPCOMING EVENTS: ORIENTATION 2016
PROJECT 1 FIRST TIME MEETING
PROJECT 1 FIRST TIME MEETING