Converting epoch time to GMT Date Time Javascript - javascript

I am currently using moment js in my application and not able to figure out how to convert epoch time to GMT date time. Providing my code below:
click: (event) => {
console.log(moment.utc(event.point.category).toDate());
}
event.point.category is providing epoch time which I want to convert to GMT date time object, but above code is converting it to local timezone date object.
For ex. 1606262400000 is getting converted to Tue Nov 24 2020 19:00:00 GMT-0500 (Eastern Standard Time) instead of GMT date time which is Wednesday, November 25, 2020 12:00:00 AM

You should get the (UTC) offset (in minutes) of the client to correct time
click: (event) => {
const offset = new Date().getTimezoneOffset();
const targetTime = moment.utc(event.point.category).toDate();
const offsetTime = new Date(targetTime.getTime() + offset * 60 * 1000);
console.log(offsetTime);
}

I believe all that you are missing is a toUTCString().
An epoch timestamp will be the same for Tue Nov 24 2020 19:00:00 GMT-0500 (Eastern Standard Time) and Wednesday, November 25, 2020 12:00:00 AM GMT
click: (event) => {
console.log(moment.utc(event.point.category).toDate().toUTCString());
}
To remain as a Date object, use moment.utc().format()

You can try something like this,
click: (event) => {
console.log(moment(moment.utc(event.point.category).toISOString()).utc());
}

Related

Weird date issue in javascript

I have a SharePoint list with delivery date column. I have created a table to display current week and next week delivery items using javascript. Everything works fine but for couple of team members Thursday delivery items are displaying in Wednesday cell and Friday items in Thursday cell.
I am not sure why it is happening. Can anyone help me out to resolve this issue? Any help would be greatly appreciated.
Here is my code. Added alerts to verify data, I am wondering why in second and third alerts sunday is showing Monday date and in third alert monday is showing Tuesday date. Added alert messages at the bottom. Please advice.
today = moment();
sundayDate = new Date(today.startOf('week'));
sundayShortDate = sundayDate.toLocaleDateString();
sundayTitle = getFormattedDate(sundayDate);
window.alert("sundayDate ::"+sundayDate+"");
monDate = new Date(sundayDate.setDate(sundayDate.getDate() + 1));
monSDate = monDate.toLocaleDateString();
monTitle = getFormattedDate(monDate);
window.alert("sundayDate ::"+sundayDate+"; monDate::"+monDate+"");
tueDate = new Date(monDate.setDate(monDate.getDate() + 1));
tuesSDate = tueDate.toLocaleDateString();
tueTitle = getFormattedDate(tueDate);
window.alert("sundayDate ::"+sundayDate+"; monDate::"+monDate+"; tueDate::"+tueDate+"");
First window alert:
sundayDate ::Sun Aug 16 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
Second Alert:
sundayDate ::Mon Aug 17 2020 00:00:00 GMT-0400 (Eastern Daylight Time); monDate::Mon Aug 17 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
Third Alert:
sundayDate ::Mon Aug 17 2020 00:00:00 GMT-0400 (Eastern Daylight Time); monDate::Tue Aug 18 2020 00:00:00 GMT-0400 (Eastern Daylight Time); tueDate::Tue Aug 18 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
As was already commented, you are mutating the dates with calls to setDate().
As you already use moment, don't switch back to Date objects, but stick to moment objects.
For example:
let today = moment();
let fmt = "dddd, MMMM Do YYYY";
let sunDate = today.startOf('week');
let sunShortDate = sunDate.format(fmt);
let monDate = sunDate.clone().add(1, "day");
let monShortDate = monDate.format(fmt);
let tueDate = monDate.clone().add(1, "day");
let tueShortDate = tueDate.format(fmt);
console.log({ sunShortDate, monShortDate, tueShortDate });
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>
Just like Date objects, also moment objects are mutable, and so you should call clone first before calling add.
You set sundayDate to sundayDate.setDate(sundayDate.getDate() + 1)
You should do:
monDate = new Date(sundayDate.getDate() + 1);
P.S.
I'm not sure if mixing moment.js and js Date is a good idea.

How to keep unique months in array of timestamps

I want to create an array that contains unique months (August 2015, September 2015 etc.). For this I defined the following function that takes an object with timestamps as keys:
export function getUniqueMonths(exps) {
//1. get all keys from expenditures
const days = Object.keys(exps)
//2. convert key strings to timestamps
const daysInt = days.map((day) => (new Date(parseInt(day))))
//3. return only the "date portion" of the timestamp
const datePortion = daysInt.map((day) => (new Date(day.toDateString()) ))
//4. set each datePortion to 1st of month
const firstOfMonth = datePortion.map((day) => new Date(day.getFullYear(), day.getMonth(), 1) )
//5. keep only unique firstOfMonths
const uniqMonths = [...(new Set(firstOfMonth))]
return uniqMonths
}
However, this function gives me an array like this:
[Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Tue Sep 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), ...]
I thought getting the date portion of the timestamp (step 3) and setting all dates to first of month (step 4) would do the trick. But I still have duplicates in my array.
What am I missing?
I think you might be overengineering things :) Something like
function getUniqueMonths(exps) {
const uniqueMonths = new Set();
Object.keys(exps).forEach((timestamp) => {
const date = new Date(parseInt(timestamp)); // expected to be milliseconds since 1/1/1970
uniqueMonths.add(`${date.getFullYear()}-${date.getMonth()}`);
});
return uniqueMonths;
}
should get you a Set of unique months in the form of ['2017-12', '2018-0', ...] (zero-based months as is the JavaScript standard).
If you need Date objects, those are trivial to "rehydrate".
Two Date objects are not the same object, even if they contain the same timestamp.
Instead, try:
//3. keep the year-month portion of the date
const yearMonths = daysInt.map(day => day.getFullYear()+"-"+day.getMonth());
Then you can skip 4 and just get the unique year-months from there. These will be returned as "2015-7" for August 2015, for example.

Why .setUTCHours returns different results?

I have the following function which should read time in UTC and return in local time, and sometimes it adds 2 hours(correctly) and sometimes 4 hours. Why is that? What can be the reason?
value = time in UTC
toLocalDate(value) {
let string = new Date(value);
let date = new Date();
date.setUTCFullYear(string.getFullYear(), string.getMonth(), string.getDate());
date.setUTCHours(string.getHours(), string.getMinutes(), string.getSeconds(), 0);
return date;
}
Example data:
Value: 2017-08-23T06:00:00
Expected output: Wed Aug 23 2017 08:00:00 GMT+0200 (Central European Daylight Time)
Output: Wed Aug 23 2017 10:00:00 GMT+0200 (Central European Daylight Time)
On some devices(like my phone or computer) it returns the expected output.
On my friend's device(mobile) it returns the second output.

How to set date always to eastern time regardless of user's time zone

I have a date given to me by a server in unix time: 1458619200000
NOTE: the other questions you have marked as "duplicate" don't show how to get there from UNIX TIME. I am looking for a specific example in javascript.
However, I find that depending on my timezone I'll have two different results:
d = new Date(1458619200000)
Mon Mar 21 2016 21:00:00 GMT-0700 (Pacific Daylight Time)
// Now I set my computer to Eastern Time and I get a different result.
d = new Date(1458619200000)
Tue Mar 22 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
So how can I show the date: 1458619200000 ... to always be in eastern time (Mar 22) regardless of my computer's time zone?
You can easily take care of the timezone offset by using the getTimezoneOffset() function in Javascript. For example,
var dt = new Date(1458619200000);
console.log(dt); // Gives Tue Mar 22 2016 09:30:00 GMT+0530 (IST)
dt.setTime(dt.getTime()+dt.getTimezoneOffset()*60*1000);
console.log(dt); // Gives Tue Mar 22 2016 04:00:00 GMT+0530 (IST)
var offset = -300; //Timezone offset for EST in minutes.
var estDate = new Date(dt.getTime() + offset*60*1000);
console.log(estDate); //Gives Mon Mar 21 2016 23:00:00 GMT+0530 (IST)
Though, the locale string represented at the back will not change. The source of this answer is in this post. Hope this helps!
Moment.js (http://momentjs.com/timezone) is your friend.
You want to do something like this:
var d = new Date(1458619200000);
var myTimezone = "America/Toronto";
var myDatetimeFormat= "YYYY-MM-DD hh:mm:ss a z";
var myDatetimeString = moment(d).tz(myTimezone).format(myDatetimeFormat);
console.log(myDatetimeString); // gives me "2016-03-22 12:00:00 am EDT"
For daylight saving, Eastern time become 4 hours behind UTC. That's why its offset is -4x60 = -240 minutes. So when daylight is not active the offset will be -300. The offset variable's value is the key point to be noted here. Kindly see this code in action in attached image.
var offset = new Date().getTimezoneOffset();// getting offset to make time in gmt+0 zone (UTC) (for gmt+5 offset comes as -300 minutes)
var date = new Date();
date.setMinutes ( date.getMinutes() + offset);// date now in UTC time
var easternTimeOffset = -240; //for dayLight saving, Eastern time become 4 hours behind UTC thats why its offset is -4x60 = -240 minutes. So when Day light is not active the offset will be -300
date.setMinutes ( date.getMinutes() + easternTimeOffset);

Converting a date string into UTC+0530 format using javascript

I have a date in the format 14-Feb-2011, but I want to convert it into the format Mon Feb 14 10:13:50 UTC+0530 2011. How Can I achieve this?
Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.
I tried this code and it returned proper date (In Indian Locale)
var d=Date.parse("14,Feb,2011");
document.write(new Date(d));
Output:
Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time) .
Here's an example of converting between different time zones.
<html>
<body>
<script type="text/javascript">
//Set you offset here like +5.5 for IST
var offsetIST = 5.5;
//Set you offset here like -8 for PST
var offsetPST = -8;
//Create a new date from the Given string
var d=new Date(Date.parse("14,Feb,2011"));
//To convert to UTC datetime by subtracting the current Timezone offset
var utcdate = new Date(d.getTime() + (d.getTimezoneOffset()*60000));
//Then cinver the UTS date to the required time zone offset like back to 5.5 for IST
var istdate = new Date(utcdate.getTime() - ((-offsetIST*60)*60000));
//Then cinver the UTS date to the required time zone offset like back to -8 for PST (Canada US)
var pstdate= new Date(utcdate.getTime() - ((-offsetPST*60)*60000));
document.write(d);
document.write("<br/>");
document.write(utcdate);
document.write("<br/>");
document.write(istdate);
document.write("<br/>");
document.write(pstdate);
</script>
</body>
</html>
Output:
Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 18:30:00 GMT+0530 (India Standard Time)
Mon Feb 14 2011 00:00:00 GMT+0530 (India Standard Time)
Sun Feb 13 2011 10:30:00 GMT+0530 (India Standard Time)
Its writing IST every where because new Date() always show date as local timezone (which is IST for me) but above datetime are actually Original, UTC, IST, PST respectively.
var d = new Date("14-Feb-2011");
this will give an output of
Mon Feb 14 2011 00:00:00 GMT-0500 (Eastern Standard Time)

Categories

Resources