Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date format like ISO but local

Tags:

javascript

how do I format a javascript date like ISO format, but in local time?

with myDate.toISOString() I am getting the time as: "2012-09-13T19:12:23.826Z"

but here, it is 22:13, so how do I include the timezone in above format?


I ended up doing...

pad=function(e,t,n){n=n||"0",t=t||2;while((""+e).length<t)e=n+e;return e} c = new Date() c.getFullYear()+"-"+pad(c.getMonth()+1)+"-"+pad(c.getDate()-5)+"T"+c.toLocaleTimeString().replace(/\D/g,':')+"."+pad(c.getMilliseconds(),3) 
like image 552
Billy Moon Avatar asked Sep 13 '12 19:09

Billy Moon


People also ask

How do I convert ISO date to local date?

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!

What is ISO date format in JavaScript?

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). The timezone is always zero UTC offset, as denoted by the suffix Z .

Is ISO 8601 same as UTC?

They're for different purposes. UTC is the primary time standard by which the world regulates clocks and time. ISO is standard format time.

Does JavaScript date get local time?

The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.


1 Answers

No library required! For some Date object, e.g. t = new Date()

  • convert the local time zone offset from minutes to milliseconds

    z = t.getTimezoneOffset() * 60 * 1000

  • subtract the offset from t

    tLocal = t-z

  • create shifted Date object

    tLocal = new Date(tLocal)

  • convert to ISO format string

    iso = tLocal.toISOString()

  • drop the milliseconds and zone

    iso = iso.slice(0, 19)

  • replace the ugly 'T' with a space

    iso = iso.replace('T', ' ')

Result is a nice ISO-ish format date-time string like "2018-08-01 22:45:50" in the local time zone.

like image 185
Denis Howe Avatar answered Oct 10 '22 05:10

Denis Howe