0

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 (e.g., '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!

Danny
  • 993
  • 4
  • 20
  • 39
  • 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:45

2 Answers2

1

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/

Krycke
  • 3,106
  • 1
  • 17
  • 21
  • Is there any way to automatically get the timezone? – Danny Sep 11 '12 at 15:30
  • 1
    There is the `getTimezoneOffset` function: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset – Chase Sep 11 '12 at 15:34
1

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

Community
  • 1
  • 1
Chase
  • 29,019
  • 1
  • 49
  • 48