I have an array like this with elements
var getDaysArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
]
I need to get the following result MM/DD/YYYY - HH:MM PM Pacific Time
I was able to replace "-" with "/" using replace
for(var i = 0; i < getDaysArray.length; i ) {
document.write(getDaysArray[i].replace("-", "/"));
}
But I need to get the following result
10/28/2021 - 19:25
CodePudding user response:
Parse your input strings into dates and transform to desired locale string with appropriate set of options:
const datesArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
],
translateDateStr = dateStr => {
const [yyyy, mm, dd, hh, mi, ss] = dateStr.split(/[-T:]/)
const date = new Date(yyyy, mm-1, dd, hh, mi, ss)
return date
.toLocaleString(
'us-PT',
{
timeZone: 'America/Los_Angeles',
hour12: false
}
)
.slice(0,-3)
.replace(', ', ' - ')
},
formattedDates = datesArray.map(translateDateStr)
console.log(formattedDates)
.as-console-wrapper{min-height:100%}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Without using an outside library like momentjs, you'll have to re-format each array element and push them into a new array.
let formattedDays = [];
for(i = 0; i < getDaysArray.length; i ) {
const date = new Date(getDaysArray[i]);
const month = date.getMonth() 1; //months go from 0-11
const day = date.getDate();
const year = date.getFullYear();
const hour = date.getHours();
const minutes = date.getMinutes();
const dateString = month "/" date "/" year " - " hour ":" minutes
formattedDays.push(dateString);
}
console.log(formattedDays);
CodePudding user response:
you had to use moment.js for this solution. your code might look like this code
var getDaysArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
]
getDaysArray.forEach(x=>{
console.log(moment(Date.parse(x), 'DD.MM.YYYY HH:mm:ss'));
})