date string that will ignore timezone offset - javascript

I am at (UTS-05:00) Eastern Time (US & Canada)
i.e, new Date().getTimezoneOffset() == 300 seconds.
Now, I have a API endpoint (JSON) that returns a date string like this.
{
someDate: '2016-01-01T00:40:00.000+00:00'
}
Here, I pass it to Date constructor like this
var dateString = "2016-01-01T00:40:00.000+00:00";
var someDay = new Date(dateString);
console.log(someDay)
Mozilla Firefox console shows
Date {Fri Jan 01 2016 00:40:00 GMT-0500 (Eastern Summer Time)}
Google Chrome console shows
Thu Dec 31 2015 19:40:00 GMT-0500 (Eastern Standard Time)
Chrome is taking the TimezoneOffset into consideration and Firefox is not. What can I do to get a Date that doesn't take Offset into consideration like FireFox in Chrome?

You can do it by:
var dates = '2016-01-01T00:40:00.000+00:00'.split(/-|T|:/);
var newDate = new Date(dates[0], dates[1]-1, dates[2], dates[3], dates[4]);

This hack works (not very clean, but does the job)
var dateString = '2016-07-27T01:40:30';
var dateParts = dateString.split(/-|T|:/);
var saneDate = new Date(
+dateParts[0],
dateParts[1] - 1,
+dateParts[2],
+dateParts[3],
+dateParts[4],
+dateParts[5]);
console.log(saneDate);

Related

How to change ISO date to Standard JS Date?

I am trying to change an ISO date to a Standard JS Date format. The JS format I am referring to is:
Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)`
What is the best way to go about doing this? Thanks!
const ISO_DATE = '2020-07-14T23:02:27.713Z';
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toString();
};
console.log(formatDate(ISO_DATE));
One way is:
let isoDate = "2020-07-20T14:29:52Z";
var myDate = new Date(isoDate);
console.log(myDate.toString()); // Mon Jul 20 2020 17:29:52 GMT+0300 ( (your time zone)
console.log("Back to ISO Date: ", myDate .toISOString());
If you want to convert it back to ISO Date use:
console.log(myDate.toISOString());

If statement with date comparison

I'm trying to write an if statement that runs some code if the date is after April 24th, 2017, 10 am EDT, but it doesn't appear that my variables are comparable (different data types?).
I'm trying to avoid using Moment.js for just this.
var today = new Date();
var launch = 'Mon Apr 24 2017 10:00:00 GMT-0400 (EDT)';
today returns Tue Apr 04 2017 14:34:41 GMT-0400 (EDT).
When I test if either is greater than the other, both are false. How should I format my dates?
Thanks!
You have to have launch as a date type:
var today = new Date();
var launch = 'Mon Apr 24 2017 10:00:00 GMT-0400 (EDT)';
var launchDate = Date.parse(launch);
if ( launchDate > today )
You should also read more about dates here:
Compare two dates with JavaScript

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);

Get exact day from date string in Javascript

I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?
Also I have looked into http://home.clara.net/shotover/datetest.htm
My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)
And I want to convert it to dd-mm-yyyy format.
I tried using:
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
But it gives me the result as: 1-6-2013
The getDay() value is the index of day in a week.
For Instance,
If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013
How can I get the proper value of Day?
P.S: I tried using .toLocaleString() and creating new date object from it. But it gives the same result.
To get the day of the month use getDate():
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
W3 schools suggests just building your days of the week array and using it:
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[d.getDay()];
Not super elegant, but usable.
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
Replace getDay() with getDate().
The above will return the local date for each date part, use the UTC variants if you need the universal time.
I think you will have to take an Array of the days & utilize it using the received index from the getDay() method.
To get required format with given date will achieve with moment.js.
a one liner solution is
import moment from "moment";
const date = new Date();
const finalDate = moment(date).format("DD-MM-YYYY")

Overriding the Javascript Date constructor?

I am developing a browser application that is sensitive to the current date.
Throughout my application's code, I call new Date and perform calculations based on the current time and render the view accordingly.
In order to test my application for different potential calendar days, I would have to constantly change my system clock to the past or future, which is an annoyance and probably not healthy for my computer.
So purely for testing purposes (I would never use this code in production), I decided to override the built-in Date constructor by doing this in the console:
// create a date object for this Friday:
var d = new Date(2012, 0, 20)
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d}
With this assumption in mind, I tried this and got strange results:
var now = new Date
Sat Apr 07 2012 00:00:00 GMT-0400 (EDT)
now = new Date
Tue Jul 10 2012 00:00:00 GMT-0400 (EDT)
now = new Date
Wed Jul 09 2014 00:00:00 GMT-0400 (EDT)
now = new Date
Wed Jun 07 2023 00:00:00 GMT-0400 (EDT)
...and so on....
My question is, what exactly is going on here?
If I overrode the constructor to return a static date, why does it give unrelated and constantly incrementing dates?
Also, is there an effective way I can override the Date constructor to return a static date in the future without having to go through all date instantiation calls in my code and modifying the output?
Thanks in advance.
EDIT:
I tried my code in a fresh window and it worked as expected.
It seems the culprit was the jQuery UI datepicker plugin which was calling its "refresh" method. When I disable its call, the date overriding works normally, but as soon as I use the datepicker, the strange behavior above occurs.
No idea why this popular plugin would somehow affect something global like this. If anyone has any ideas, let me know.
Sorry for not figuring out the true culprit earlier.
I also faced this problem and ended up writing a module for that. Perhaps it's useful for somebody:
Github: https://github.com/schickling/timemachine
timemachine.config({
dateString: 'December 25, 1991 13:12:59'
});
console.log(new Date()); // December 25, 1991 13:12:59
I tested your code:
// create a date object for this Friday:
var d = new Date(2012, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date()
console.log(now);
now = new Date()
console.log(now);
now = new Date()
console.log(now);
now = new Date()
console.log(now);
And the result ???? Why so different?
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
EDIT:
I saw that whenever you interact with the Date Picker, the behavior goes different. Try another test, change the now is something like interact with Date Picker:
// create a date object for this Friday:
var d = new Date(2012, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date();
var another = new Date();
console.log(now);
another.setDate(13);
now = new Date()
console.log(now);
And the result is:
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 13 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
So, what goes wrong?
You already overridden core Date function by
Date = function(){return d;}; // after construction, all date will be d (2012-01-20)
var now = new Date(); // you instantiate a date, but actually now variable is d (2012-01-20)
var another = new Date(); // you instantiate a date, but another is still d (2012-01-20)
another.setDate(13); // change another date to 13 is to change now to 13 (because now and another is still one d)
now = new Date() // still d
console.log(now); // print out now (2012-01-13)
So, you overrides core Date function by a function that causes all date use the same (just one) instance, which is d (2012-01-20). Change any dates affect others.
This is working for me.
I.E how to return process time 1 minute back
Date = class extends Date{
constructor(options) {
if (options) {
super(options);
} else {
super(Date.now() - 1000 * 60);
}
}
};
Give this a shot.
var d = new Date(2012, 0, 20);
// undefine date so that it will only return what your function returns
Date = undefined;
Date = function(){return d;}
Modifying the prototype to point to your object should do the trick.
I believe the strange behavior you were experiencing earlier was that privately Date holds some notion of time, and since the prototype points to that internal clock, you were getting random times.
Alex Stanovsky's answer almost did it for me but this modification made the constructor work like before when given parameters.
Date = class extends Date {
constructor(...options) {
if (options.length) {
super(...options);
} else {
super(2019, 2, 11, 19, 19);
}
}
};
I used the below to enforce UTC dates
var _f = function(item) {
Date.prototype["get" + item] = Date.prototype["getUTC" + item];
Date.prototype["set" + item] = Date.prototype["setUTC" + item];
}
var _d = ['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'];
_d.forEach(_f);
Date = class extends Date {
constructor(...options) {
if (options.length == 1 && options[0].constructor == Date) {
super(options[0]);
} else if (options.length > 0) {
super(Date.UTC(...options));
} else {
super(Date.UTC());
}
}
};

Categories

Resources