Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Javascript date format like ISO but local

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)
question from:https://stackoverflow.com/questions/12413243/javascript-date-format-like-iso-but-local

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...