简体   繁体   中英

get UTC timestamp from formated date - javascript

I have a UTC date string -> 10/30/2014 10:37:54 AM

How do I get the timestamp for this UTC date? As far as I know, following is handling this as my local time

var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime();

Thank you

You can use Date.UTC to create a UTC format date object.

Reference:

 (function() { var d = new Date(); var d1 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds())); console.log(+d); console.log(+d1); })() 

如果格式是固定的,则可以轻松解析它并使用Date.UTC() API。

You can decrease the "TimezoneOffset"

var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime() - (d.getTimezoneOffset() *1000 * 60);

Also u can use the UTC function

var d = new Date("10/30/2014 10:37:54 AM");
return Date.UTC(d.getFullYear(),d.getMonth()+1,d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds());

A quick hack would be to append UTC to the end of your string before parsing:

var d = new Date("10/30/2014 10:37:54 AM UTC"); 

But I would advise you to use a library like moment.js, it makes parsing dates much easier

Try Date.parse

var d = new Date("10/30/2014 10:37:54 AM");
var timstamp = Date.parse(d) / 1000;

Hope this helps:

Date date= new Date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

    date = sdf.parse(date.toString());
    String timestamp = sdf2.format(date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM