1

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

eder
  • 45
  • 1
  • 10
  • Can you use a library like momentjs? http://momentjs.com/docs/#/parsing/unix-timestamp/ – Oakley Dec 18 '15 at 11:57
  • Doesn't getTime() returns timestamp in UTC only? See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime – n4m31ess_c0d3r Dec 18 '15 at 12:04
  • Possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – John Slegers Feb 19 '16 at 21:46

6 Answers6

2

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);
})()
Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66
1

If the format is fixed, you could easly parse it and use the Date.UTC() API.

Davide Ungari
  • 1,750
  • 1
  • 11
  • 20
1

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());
Adi Darachi
  • 1,781
  • 1
  • 11
  • 26
  • why did you add a +1 behind d.getMonth()? – eder Dec 18 '15 at 12:28
  • The month value is 0 based. Meaning that "0" is January, "1" is February. But the Date.UTC function expecting 1 based value meaning that "1" is January... and so on, that why we add the +1. – Adi Darachi Dec 18 '15 at 12:36
0

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

caffeinated.tech
  • 5,846
  • 19
  • 36
0

Try Date.parse

var d = new Date("10/30/2014 10:37:54 AM");
var timstamp = Date.parse(d) / 1000;
Mario Shtika
  • 1,087
  • 12
  • 28
0

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);
krpa
  • 54
  • 1
  • 13