Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why converting new.Date() .toISOString() changes the time?

I'm inserting a date in a database in two different format.

this is inserting as Datetime

    var mydate;
    mydate = new Date();
    document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');

Output A

2017-06-21 20:14:31 

this is inserting as varchar :

document.getElementById('clocked_in_time').value = Date();

Output B

Wed Jun 21 2017 16:14:31 GMT-0400 (Eastern Standard Time)

Output B is the correct time but I need to display output A. What causes the time to change when converted toISOString? How can I fix this?

like image 827
Sebastian Farham Avatar asked Jun 22 '17 03:06

Sebastian Farham


People also ask

How do you convert toISOString to dates?

Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z') . The Date() constructor will easily parse the ISO 8601 string and will return a Date object. Copied! We used the Date() constructor to create a Date object from an ISO string.

What is the format of new date ()?

The most used method to get the date in JavaScript is the new Date() object. By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time).

What is toISOString in JavaScript?

toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively).

How do I change the date on an ISO file?

The date. toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ).


2 Answers

ISO time is time zone free. You'll notice with b you have time zone GMT-04:00 if you add those four hours to the 16 hours in the Date, you get 20

like image 27
ControlAltDel Avatar answered Oct 12 '22 17:10

ControlAltDel


In your this is inserting as Datetime block your slice are stripping of the timezone part (the Z at the end of toISOString output):

document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');

As pointed out by @RobG in the comments section, toISOString should always return the date in UTC (Z or +00:00).

RTFM: "The time zone [offset] is always UTC, denoted by the suffix Z",

The time "changes" because it is converted to UTC when you calls toISOString.

If you want to get ISO date in your timezone, you should take a look in these two questions: How to ISO 8601 format a Date with Timezone Offset in JavaScript? and How to format a JavaScript date

like image 74
Dinei Avatar answered Oct 12 '22 18:10

Dinei