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

3

6 Answers 6

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);
})()

Sign up to request clarification or add additional context in comments.

Comments

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());

2 Comments

why did you add a +1 behind d.getMonth()?
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.
1

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

Comments

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

Comments

0

Try Date.parse

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.