Martin Ille
Martin Ille

Reputation: 7055

get UTC timestamp from today's local time

Let's assume I know this time (hh:mm:ss) without date but I know it is today:

12:34:56

And I know the time is in CST timezone (UTC +0800). I need to get timestamp from the time.

Let's assume current UTC time is 2014/08/25 17:10:00 and CST is 2014/08/26 01:10:00 (UTC +0800) so it means in CST is already the next day. Therefore I can't use something like this:

var d = new Date().toJSON().slice(0,10);
// "d" returns "2014-08-25" in local time -> this is bad

I need to convert this:

1:10 (CST) --> to 2014/08/25 17:10 (UTC) or its timestamp 1408986600

How can I get full date-time or timestamp when I know the time and timezone only?

Upvotes: 0

Views: 654

Answers (2)

Martin Ille
Martin Ille

Reputation: 7055

I think I found the easy way using moment-timezone.js:

// hh:mm:ss in CST timezone
var cst_time = '1:10:00'; 

// get today's date in CST timezone
var cst_today = moment.tz("Asia/Shanghai").format("YYYY-MM-DD"); 

// convert date and time from CST to UTC and format it
var timestamp = moment(cst_today + " " + cst_time + " +0800").utc().format("YYYY/MM/DD HH:mm:ss");

// returns "2014/08/25 17:10:00" and it is correct
console.log(timestamp); 

Upvotes: 0

tadman
tadman

Reputation: 211560

You can always manipulate the properties of a Date object directly:

var date = new Date();

date.setHours(5);
date.setMinutes(12);
date.setSeconds(10);

console.log(date.toUTCString());

Upvotes: 1

Related Questions