kat1330
kat1330

Reputation: 5332

Convert year string into date

I want to convert year string into a date type like in the following example:

var date = new Date('1999');
console.log(date); // result -> Thu Dec 31 1998 16:00:00 GMT-0800 (Pacific Standard Time)

The problem is with time zone. Because the string is not properly formated and it is treated as UTC time zone.

How to convert year string properly and treat as local time?

I know that it will work if I append day and month like this '01/01/' + '1999' but is it possible some other solution?

Upvotes: 0

Views: 178

Answers (3)

Chris Halcrow
Chris Halcrow

Reputation: 31950

You should always declare any date variables using UTC explicitly, then convert them when you need to. Declare the date in UTC first then convert it to a string. So I think you need:

var date = new Date('1999-01-01 08:00:00 UTC');
console.log(date.toString());

Upvotes: 0

Sotiris Kiritsis
Sotiris Kiritsis

Reputation: 3336

You should first create a new Date object with the current timezone, then get your timezone offset and then subtract it from it.

The getTimezoneOffset() method returns the time zone difference, in minutes, from current locale (host system settings) to UTC.

The following should work:

var x = new Date().getTime() - new Date().getTimezoneOffset();
var y = new Date(x);
console.log(y);

You can also try it online on jsfiddle.

Upvotes: 0

Will Reese
Will Reese

Reputation: 2841

You can initialize a date with an empty value to avoid problems with default properties.

var date = new Date("");
date.setYear(1999);

Upvotes: 1

Related Questions