简体   繁体   中英

Convert Date and Time into a UTC formatted Date - Javascript

I have two variables, date & time...

var date = "2012-12-05";
var time = "18:00";

How can I format this into a UTC formatted date. This is so I can use it within the Facebook API..

Facebook states I need it in this format:

Precise-time (eg, '2012-07-04T19:00:00-0700'): events that start at a particular point in time, in a specific offset from UTC. This is the way new Facebook events keep track of time, and allows users to view events in different timezones.

Any help would be much appreciated.. Thanks!

This format is called ISO 8601

Do you know what timezone you are in? If you do, you can do like this:

var datetime = date + 'T' + time + ":00+0000';

if the timezone is +0.
if not, then:

var d = new Date()
var n = d.getTimezoneOffset();
var timeZone = Math.floor( Math.abs( n/60 ) );
var timeZoneString = (d.getTimezoneOffset() < 0 ? '-' : '+' ) + ( timeZone < 10 ? '0' + timeZone : timeZone ) + '00';

var datetime = date + 'T' + time + ':00' + timeZoneString;

Here is a fiddle: http://jsfiddle.net/ajySr/

Try the following:

var date = new Date(2012, 12, 5, 18, 0, 0, 0); 
var date_utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());

The Date function can be used the following ways:

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

This was taken from a related post here: How do you convert a JavaScript date to UTC?

To find out more, please refer to: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/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