5

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
M.Izzat
  • 936
  • 2
  • 15
  • 43
  • Possible duplicate of [Convert ISO Date to Date Format yyyy-mm-dd format in javascript](https://stackoverflow.com/questions/25159330/convert-iso-date-to-date-format-yyyy-mm-dd-format-in-javascript) – SamVK Nov 02 '17 at 02:25
  • ` now = (new Date()).toISOString(); now = now.split("T")[0];` – Bekim Bacaj Nov 02 '17 at 02:30

4 Answers4

12

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.

Ramy M. Mousa
  • 5,301
  • 3
  • 37
  • 43
10

One simple but robust approach is to split along the date separator:

new Date().toISOString().split('T', 1)[0] // => '2019-03-18'

If working with an ISO string of unknown origin, using a Regex pattern as the splitter may prove more reliable (ie. Postgres uses a whitespace as the separator).

const isoString = '2019-01-01 12:00:00.000000'

isoString.split(/[T ]/i, 1)[0] // => '2019-01-01'

Unlike using substring, this approach does not make assumptions about the length of the date (which might prove false for years before 1000 and after 9999).

Minty Fresh
  • 633
  • 4
  • 14
2

Here's how it would be done with momentjs

var currentDate = moment().format('YYYY-MM-DD');

Check out the Jsfiddle link: https://jsfiddle.net/cgbcc075/

Chol Nhial
  • 1,227
  • 1
  • 8
  • 24
1

It's better to use moment in js for date time related functions. Instantly now you can use substring method: var a = "2017-10-19T16:00:00.000Z" a = a.substring(0,10)

karthik reddy
  • 479
  • 4
  • 12