Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove time after converting date toISOString

how can I remove the time after converting a date to ISO String?

var now = new Date();
console.log( now.toISOString() );

if the output is

2017-10-19T16:00:00.000Z

I just want it to be :

2017-10-19
like image 276
M.Izzat Avatar asked Nov 02 '17 02:11

M.Izzat


People also ask

Why does the time change when I use toisostring?

The time "changes" because it is converted to UTC when you calls toISOString. If you want to get ISO date in your timezone, you should take a look in these two questions: How to ISO 8601 format a Date with Timezone Offset in JavaScript? and How to format a JavaScript date

What is date toisostring () method in JavaScript?

Below is the example of Date toISOString () method. The date.toISOString () method is used to convert the given date object’s contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ).The date object is created using date () constructor.

How to convert a date object to a string?

The toISOString() method converts a Date object into a string, using the ISO standard. The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ

Does toisostring always return the date in UTC?

As pointed out by @RobG in the comments section, toISOString should always return the date in UTC ( Z or +00:00 ). The time "changes" because it is converted to UTC when you calls toISOString.


1 Answers

There are actually many ways to do so:

1- Use Moment JS which gives you kind of flexibility in dealing with the issue

2- The simple way to do it in native JS is to use substr() function like that:

var date = new Date();
console.log(date.toISOString().substr(0,10));

The second way would be more effective if all you need is to remove the time part of the string and use the date only.

like image 127
Ramy M. Mousa Avatar answered Oct 25 '22 14:10

Ramy M. Mousa