2

I use Angular 5.

I am going to convert string to date.

My code is:

const start_date = '2015-02-03';
const startDate = new Date(start_date);
console.log(startDate);
console.log(startDate.getDate()); // startDate.getDate() is my target

The output of this code is:

Mon Feb 02 2015 19:00:00 GMT-0500 (Eastern Standard Time)
2

But I want to get 3 as a result.

How can I solve this without using Timezone?

Akshay Kumar
  • 115
  • 1
  • 2
  • 7
  • If all you want is the date, then `+start_date.slice(-2)` does the job without the vagaries of the built–in parser and in less code. ;-) – RobG Nov 30 '18 at 21:43

2 Answers2

1

It is simply.

Try like this:

const start_date = '2015-02-03';
const startDate = new Date(start_date + ' 00:00:00');
console.log(startDate);
console.log(startDate.getDate());
Igor Carvalho
  • 668
  • 5
  • 19
  • 2
    Non standard ISO format like that may parse differently in different browsers/environments – charlietfl Nov 29 '18 at 17:48
  • @Igor Carvalho, I solved it and it works well. Thanks for your help. – Akshay Kumar Nov 29 '18 at 20:59
  • 1
    Returns an invalid date in Safari as the format is not consistent with ECMA-262. Code only answers aren't helpful, you should explain why the OP has their issue and how your answer fixes it. – RobG Nov 30 '18 at 21:41
0

Simple. You can use .toUTCString() which returns the date in UTC time as function suggest.

In your case:

const start_date = '2015-02-03';
const startDate = new Date(start_date);
console.log(startDate);
console.log(startDate.toUTCString()); 
Beto Silva
  • 58
  • 6