comapre javascript toUTCString() with UTC date time - javascript

From Authentication API along with token i am getting its expiry date time which is in UTC
I am using npm jwt-decode package to extract the info
private setToken(value: string) {
this._token = value;
var decoded = jwt_decode(value);
this._expiry = new Date(decoded['expiry']);
}
To check if token expired i compare it with current UTC dat time
isTokenExpired() {
var currentUTC = new Date().toUTCString() as any;
var flag = this._expiry < (currentUTC as Date);
if (flag)
return true;
else
return false;
}
but new Date().toUTCString() gives strig instaed of date which always retuen false when compare with date object
I tried to convert it to date but after conversion it show date as per browser local time zone instead of actual utc date time
console.log('current UTC : '+ currentUTC);
console.log('expiry UTC : '+ this._expiry);
console.log('utc string to UTC Date : ' + this.createDateUTC(currentUTC));
console.log(new Date(Date.parse(currentUTC as string)));
console.log(this._expiry < (currentUTC as Date));
createDateUTC(dateUTC) {
return new Date(dateUTC + "Z");
}
output is as follow
current UTC : Fri, 02 Sep 2022 02:32:21 GMT
expiry UTC : Fri Sep 02 2022 03:32:08 GMT+0530 (India Standard Time)
utc string to UTC Date : Invalid Date
Fri Sep 02 2022 08:02:21 GMT+0530 (India Standard Time)
Current UTC is correct
expiry UTC is correct , Current UTC + 1 hours as expiry time returned from api
third one is converted to date which is invalid date , Ref : stack overflow Post by Killer
fourth one , tried to parse but it after parsing its local time. UTC time lost.
Any idea how to convert UTC string to date object without loosing its actual value, or any other approach to get current UTC date time
Update 1 :
After refresh
this._expiry = new Date(decoded['expiry'])
inside setTokn() method also lost UTC date time and convert it as per local time
Update 2:
Tried code by "HsuTingHuan" but got same result. Issue persist

I had met similar case before. Hope my solution can help you
I was used the javascript Date object's toISOString() function or JSON.stringnify()(Because the JSON object will always convert to ISO 8601 format)
And compare all of the datetime object by ISO 8601 format
example works on EDGE:
var currentUTC = new Date().toISOString();
console.log(currentUTC)
function createDateUTC(dateUTC) {
return new Date(dateUTC);
}
var currentUTCDateobj = createDateUTC(currentUTC)
console.log(currentUTCDateobj)
var expiry = new Date("2022-09-02 00:00:00")
console.log(expiry)
console.log(expiry < currentUTCDateobj);

Related

Creating a Date is adding automatically one hour to my input date

let's say I have this date as input :
var _dateA = 2018-11-15T11:13:26.687Z
If I'm doing, whatever,
var _dateB = new Date(_date)
or
var _dateB = moment(_date)
I get this as result ==>
_dateB = Thu Nov 15 2018 12:13:26 GMT+0100 (heure normale d’Europe centrale)
I understood that there's timezone trouble, but how can I get a Date object or Moment object, without having this one hour more?
Wanted result => Thu Nov 15 2018 11:13:26 GMT+0100
Current result => Thu Nov 15 2018 12:13:26 GMT+0100
You need to use Date.toUTCString() that converts date to string, using the UTC time zone
var _dateA = '2018-11-15T11:13:26.687Z';
var _dateB = new Date(_dateA);
console.log(_dateB.toUTCString());
When you "output" a Date object via console.log(), alert(), etc the toString() method is used by default, converting the date object to a local timezone string for display (which is why you are seeing your date in your local time).
Parsing date strings with the Date constructor is not recommended (although, I suspect that most browsers probably handle ISO 8601 dates, like the one in your question, fairly well) - see the dateString parameter note here. So, if you need to construct a date object as well as output a date string, then you could parse the ISO 8601 string with split() using a regex character set for multiple delimiters, then construct a UTC date object with new Date(Date.UTC(...)). You could also do this with moment.js but the below should illustrate what is happening in a bit more detail.
For example:
const text = '2018-11-15T11:13:26.687Z'
const [y, m, d, hh, mm, ss, ms] = text.split(/[-T:.Z]/);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(date.toLocaleString()); // date string in local timezone
console.log(date.toUTCString()); // UTC date string
console.log(JSON.stringify(date)); // ISO 8601 date string in most browsers

JavaScript "new Date" creating date with time different from original date string

I am getting a date as a string '2018-10-15 00:00:00.000', then converting it to a date using new Date('2018-10-15 00:00:00.000').
I am persisting this date to a database (with API) and it is saving the data as 2018-10-15 **04**:00:00.000. Note the 4 am time. The API gets the date time as 4:00 am.
In my angular application, the object that holds this date is defined as Date type.
meeting_date: Date;
This is from the console.
dt = new Date('2018-10-15 00:00:00.000')
Mon Oct 15 2018 00:00:00 GMT-0400 (Eastern Daylight Time)
JSON.stringify(dt)
""2018-10-15T04:00:00.000Z""
I want to save the date as 2018-10-15 00:00:00.000. What am I doing wrong?
If the date input string you are getting represents UTC, then you probably want to create the Date object in UTC (your current approach is creating the Date object in local time on the client machine, which is why the EDT offset is affecting the datetime you are storing in your db). Also, you should be aware that Date() is not recommended for parsing date strings due to browser inconsistencies.
Following is an example using some simple regex to parse the string and create the Date object in UTC:
const str = '2018-10-15 00:00:00.000';
const [y, m, d, hh, mm, ss, ms] = str.match(/\d+/g);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(JSON.stringify(date));
// date as UTC string
console.log(date.toUTCString());
// date as local string
console.log(date.toString());

JavaScript Date Object - How Do You Convert a Generic Date to Start of Day Today?

I have a date in string format that looks like:
2016-11-02
I use date('2016-11-02') to convert it to a JavaScript date object. My local timezone is EST and the above will return:
Tue Nov 01 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
I would like the generic date input above (without a timestamp) and the date function to return:
Wed Nov 02 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
How would I do this?
According to ECMA-262, a string like "2016-11-02" should be parsed as UTC, so in time zones with an offset other than 00:00, it will represent some time other than 2016-11-02 00:00:00.
If you want an ISO 8601 format date string to be parsed as local, you will have to do it yourself or use a library. A simple function to parse as local is:
/* Parse an ISO 8601 format date string as local
** #param {string} s - date in yyyy-mm-dd format
** #returns {Date} "local" date for provided string, or an
** invalid date if string is invalid.
*/
function parseISOasLocal(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
console.log(parseISOasLocal('2016-11-02').toLocaleString());
You could do the following:
var myDate = '2016-11-02';
// UTC
console.log(new Date(myDate).toUTCString());
// Local
console.log(new Date(myDate).toTimeString());
The first log will return you the UTC time and the second will give you the local time.

get UTC timestamp from today's local time

Let's assume I know this time (hh:mm:ss) without date but I know it is today:
12:34:56
And I know the time is in CST timezone (UTC +0800). I need to get timestamp from the time.
Let's assume current UTC time is 2014/08/25 17:10:00 and CST is 2014/08/26 01:10:00 (UTC +0800) so it means in CST is already the next day. Therefore I can't use something like this:
var d = new Date().toJSON().slice(0,10);
// "d" returns "2014-08-25" in local time -> this is bad
I need to convert this:
1:10 (CST) --> to 2014/08/25 17:10 (UTC) or its timestamp 1408986600
How can I get full date-time or timestamp when I know the time and timezone only?
You can always manipulate the properties of a Date object directly:
var date = new Date();
date.setHours(5);
date.setMinutes(12);
date.setSeconds(10);
console.log(date.toUTCString());
I think I found the easy way using moment-timezone.js:
// hh:mm:ss in CST timezone
var cst_time = '1:10:00';
// get today's date in CST timezone
var cst_today = moment.tz("Asia/Shanghai").format("YYYY-MM-DD");
// convert date and time from CST to UTC and format it
var timestamp = moment(cst_today + " " + cst_time + " +0800").utc().format("YYYY/MM/DD HH:mm:ss");
// returns "2014/08/25 17:10:00" and it is correct
console.log(timestamp);

Json Date to JavasScript Date Conversion problem

Heres the code for converting the json retured date to a string of date.
String.toDate = function(stringDate) {
var newDate = new Date(parseInt(stringDate.replace("/Date(", "").replace(")/", ""), 10));
return newDate;
}
Here are the details:
Date from the database: 2009-11-18 03:23:25.107
Date Returned by JSON: "/Date(1258514605107)/"
Date Returned by the toDate function :
Wed Nov 18 2009 11:23:25 GMT+0800 (Taipei Standard Time)
Web Server and Database server time zone are the same.
Im wondering why the date becomes the current date in my timezone.
Is there anyone here encountered this kind of problem?
and what about your browser/OS settings ? you need the GMT time ?
I think you get get it with toUTCString a more complete reference about the date class
alert(newDate.toUTCString());

Categories