Reputation: 5182
I have this list of times in timezone "-07:00" and I want to convert them to "+05:00".
"hours": [
{
"from": "11:00",
"to": "21:00",
"dayOfWeek": "MONDAY"
},
{
"from": "11:00",
"to": "21:00",
"dayOfWeek": "TUESDAY"
},
{
"from": "11:00",
"to": "21:00",
"dayOfWeek": "WEDNESDAY"
},
{
"from": "11:00",
"to": "21:00",
"dayOfWeek": "THURSDAY"
},
{
"from": "11:00",
"to": "21:00",
"dayOfWeek": "FRIDAY"
}
]
How to do this efficiently using a library like moment.js? I have worked on a method but it's not up to par.
function formatDates(hoursList, shopDate, userDate){
var moment = require('moment');
var selectedDateText = "";
var convertedDateList = [];
for (var x = 0; x < hoursList.length; x++) {
var fromDate = shopDate.clone();
var fromMoment = moment(fromDate.format(), "YYYY-MM-DD HH:mm Z");
var fromTime = fromMoment.utcOffset(userDate.utcOffset());
fromTime.hours(parseInt(hoursList[x].from.split(":")[0]));
fromTime.minutes(parseInt(hoursList[x].from.split(":")[1]));
fromTime.seconds(0);
fromTime.milliseconds(0);
console.log(fromTime.format());
var toDate = shopDate.clone();
var toMoment = moment(toDate.format(), "YYYY-MM-DD HH:mm Z");
var toTime = toMoment.utcOffset(userDate.utcOffset());
toTime.hours(parseInt(hoursList[x].to.split(":")[0]));
toTime.minutes(parseInt(hoursList[x].to.split(":")[1]));
toTime.seconds(0);
toTime.milliseconds(0);
console.log(toTime.format());
var initialDay = {
"from": "",
"to": "",
"dayOfWeek": ""
};
initialDay.dayOfWeek = fromTime.format("dddd").toUpperCase();
initialDay.from = fromTime.format("HH:mm");
if (toTime.format("DDD") != fromTime.format("DDD")) {
var secondaryDay = {
"from": "",
"to": "",
"dayOfWeek": ""
};
initialDay.to = "24:00";
secondaryDay.dayOfWeek = toTime.format("dddd").toUpperCase();
secondaryDay.from = "00:00";
secondaryDay.to = toTime.format("HH:mm");
convertedDateList.push(secondaryDay);
} else {
initialDay.to = toTime.format("HH:mm");
}
convertedDateList.push(initialDay);
}
console.log(convertedDateList);
return selectedDateText;
}
Major problem is, some time stamps when converted will be in 2 different days. Hence the initial and secondary day in the code. Ex: When it's some 6 hours and it gets split in two, it should be added as Monday 9PM - 12PM and Tuesday 12AM - 3AM. And this is even trickier when it's an instance where the hours have all 7 days and some days, after conversion will even have hours from 12AM - 3AM and 9PM to 12PM.
How to tackle this properly?
Thanks.
Upvotes: 1
Views: 72
Reputation: 1220
For timezone related Moment has made a module dependent on moment.js - please find the documentation here
Upvotes: 1