9

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
  • 1,086
  • 4
  • 22
  • 50
  • 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

6 Answers6

13

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
  • 663
  • 4
  • 14
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 substring() function like that:

var date = new Date();
console.log(date.toISOString().substring(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.

Community
  • 1
  • 1
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
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,327
  • 1
  • 10
  • 25
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
1

The easiest way is just to use split

var now = new Date();
console.log(now.toISOString().split('T')[0]);
ksawery297
  • 58
  • 1
  • 6
1

Computationally fastest way (ie: no unnecessary allocations) would be slicing up to index 10, since ISO8601 timestamp strings have these elements guaranteed, at least for the years 0000 to 9999.

let currentDate = new Date().toISOString().substring(0,10);
djtubig-malicex
  • 1,018
  • 1
  • 7
  • 11