Aviram Adiri
Aviram Adiri

Reputation: 105

Convert string to Date without considering timezone - Typescript

I'm getting a date as a string, in the following format (for example):

"11/10/2015 10:00:00"

This is UTC time.

When I create Date from this string, it consider it as local time:

let time = "11/10/2015 10:00:00";
let date = new Date(time); 
console.log(date);

it prints:

"Tue Nov 10 2015 10:00:00 GMT+0200"

(instead of considering it as UTC: "Tue Nov 10 2015 10:00:00")

I also tried moment.js for that.

is there a good way to make Date() consider the string a UTC, without adding "Z"/"UTC"/"+000" in the end of the string?

Upvotes: 2

Views: 4981

Answers (4)

Christophe
Christophe

Reputation: 699

Easy answer is to append a "Z" at the end without changing the variable:

let time = "11/10/2015 10:00:00";  
let date = new Date(time + "Z");  
console.log(date);

Upvotes: 1

bbsimonbb
bbsimonbb

Reputation: 28992

Your date is parsed by the date constructor, in MM/DD/YYYY format, applying the local timezone offset (so the output represents local midnight at the start of the day in question). If your date really is MM/DD/YYYY, all you need to do is subtract the timezone offset and you'll have the UTC date...

var myDate = new Date("11/10/2015 10:00:00");
myDate = new Date( myDate.getTime() - (myDate.getTimezoneOffset()*60*1000));
console.log(myDate.toLocaleString([],{timeZone:'UTC'}))

Here's everything I know about managing timezone when serializing and deserializing dates. All the timezone handling is static! JS dates have no intrinsic timezone.

Upvotes: 2

mhodges
mhodges

Reputation: 11116

You can use the built-in Date.UTC() function to do this. Here's a little function that will take the format you gave in your original post and converts it to a UTC date string

let time = "11/10/2015 10:00:00";

function getUTCDate(dateString) {
  // dateString format will be "MM/DD/YYYY HH:mm:ss"
  var [date, time] = dateString.split(" ");
  var [month, day, year] = date.split("/");
  var [hours, minutes, seconds] = time.split(":");
  // month is 0 indexed in Date operations, subtract 1 when converting string to Date object
  return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)).toUTCString();
}

console.log(getUTCDate(time));

Upvotes: 3

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

You can use Date.UTC for this but you will have to parse your string and put every part of it as args by yourself as it can't parse such string. Also you could use moment.js to parse it: Convert date to another timezone in JavaScript

Also, seems like new Date("11/10/2015 10:00:00 GMT") parses date as a GMT and only after that converts it to PC local time

Upvotes: 0

Related Questions