Reputation: 37
I have an array of dates which starts from 1950 up till 2019. Task is to filter the date so that dates array contains dates after 1970 and we need to map the dates to the given format like change the format.
let dateformat="April 2015"
var endDate = ["1950-09-02T23:00:00.000Z",
"1951-06-02T23:00:00.000Z"
..........
"2016-09-02T23:00:00.000Z",
.........
"2019-09-02T23:00:00.000Z"]
my solution:
endDate.filter(item => item > 1970).map(item => item = new Date(dateFormat))
Expected result is that date array changes the dates from given format to April 2015 - Month - year only. I am able to filter dates so that date are greater than 1970 but not able to map to the given format. Also I am trying to do it using ES6 syntax. The array was generated dynamically by pushing the dates into array.
Upvotes: 1
Views: 1135
Reputation: 498
Just for kicks, an alternative utilizing the sortability of the the ISO date format. Also prevents conversion from UTC causing edge case where year may be 1969 in local time zone.
const input = ["1950-09-02T23:00:00.000Z",
"1951-06-02T23:00:00.000Z",
"2016-09-02T23:00:00.000Z",
"1970-01-01T00:00:00.000Z",
"1969-12-31T23:59:59.999Z",
"2019-09-02T23:00:00.000Z"
];
// ISO date format string is sortable already
const sorted = input.sort();
// find the first date greater than or = 1970
const firstIdx = sorted.findIndex(d => Number(d.substring(0,4)) >= 1970);
// take all of the dates after the first one with 1970
const output = sorted.slice(firstIdx)
// keep date formatting in UTC timezone like the input dates,
// otherwise depending on local time zone, the year may be 1969
.map(d => new Date(d).toLocaleString('default', {timeZone: 'UTC', month: 'long', year: 'numeric'}));
console.log(output);
Upvotes: 0
Reputation: 193258
Map the strings to Date
objects, filter by the year, and then map the dates to the requested format using Date.toLocaleString()
:
const dateformat = "April 2015"
const endDate = ["1950-09-02T23:00:00.000Z", "1951-06-02T23:00:00.000Z", "2016-09-02T23:00:00.000Z", "2019-09-02T23:00:00.000Z"]
const result = endDate
.map(item => new Date(item))
.filter(item => item.getFullYear() > 1970)
.map(item => item.toLocaleString('en-US', {
month: 'long',
year: 'numeric'
}))
console.log(result)
Upvotes: 2
Reputation: 395
This is very close to Ori Drori's answer, but with a single loop:
const endDate = [
"1950-09-02T23:00:00.000Z",
"1951-06-02T23:00:00.000Z",
"2016-09-02T23:00:00.000Z",
"2019-09-02T23:00:00.000Z"
]
const dates = endDate.reduce((dates, date) => {
date = new Date(date)
date.getFullYear() > 1970 && dates.push(date.toLocaleString('en-US', {
month: 'long',
year: 'numeric'
}))
return dates
}, [])
console.log(dates)
Upvotes: 1