0

I have a input date format which is like 1 April 2018. I need to convert it to the format 2018-04-01. while I am using the following code :

var dateinput = new Date('2 April 2018').toISOString();
alert(dateinput);

The reuslt I am getting is :

2015-04-01 T18:30:00.000Z

which is 1 day less than what I input. Also how do I remove the part T18:30:00.000Z from the date function?

Udit Gogoi
  • 675
  • 2
  • 11
  • 28
  • Why not use simple format method: https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date ? – Beri Mar 26 '18 at 07:56

2 Answers2

1

The issue you are getting is due to the use of Date.parse() behind the scenes when you build your new Date instance. This is something that's actually not recommended, as is described on the MDN page for Date :

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

If your input format is simple enough (i.e. always number of day followed by month followed by year, with valid values), your best bet is probably to create a function that parses your input string and builds a Date object using Date.UTC() or the setUTC*() functions. And write another function that takes a Date object and builds a string in your target format using the getUTC*() methods. That way you are sure your date will not be off, and not bothered by timezones.

If your use case is actually more complicated than that (multiple input and output formats), it is probably better to look into using a library like moment.js.

KevinLH
  • 328
  • 3
  • 10
0
function formatDate(date) {
// Get timezone offset in ms
var offset = (new Date()).getTimezoneOffset() * 60000;

// Get iso time and slice timezone
var dateWithoutTimeZone = (new Date(new Date(date) - offset)).toISOString().slice(0,-1);

var d = new Date(dateWithoutTimeZone);

var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();

return `${year}-${(month > 9 ? '' : '0') + month}-${(day > 9 ? '' : '0') + day}`;
} 

formatDate('2 April 2018') // -> "2018-04-02"
Efe
  • 5,180
  • 2
  • 21
  • 33