0

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?

2
  • stackoverflow.com/questions/2613511/… Commented Jun 15, 2017 at 1:47
  • new Date(1999, 0) should do. Pass it as year+month parameters, not a string to be parsed. Commented Jun 15, 2017 at 5:54

3 Answers 3

1

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

var date = new Date("");
date.setYear(1999);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.