3

I am trying to convert date object to ISOString() formate. But it return me 1 day off ( I mean it reduce 1 day ).

var fromDate = { 
  day:4,
  month:5,
  year:2012
 }
 var fromDateString = new Date(fromDate.year+'-'+fromDate.month+'-'+fromDate.day)
 console.log(fromDateString.toISOString())
  • Does this answer your question? [Converting a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript) – ShadowRanger Nov 11 '20 at 06:00
  • Check this post https://stackoverflow.com/questions/64464146/date-time-is-changing-depending-on-environment – hyundeock Nov 11 '20 at 06:48
  • Or simply: new Date(2022,6,1).toISOString() returns, for me, "2022-06-30..." which just seems like nonsense – PandaWood Aug 03 '22 at 05:39

2 Answers2

0

It is because of timezone, new Date() is in your current timezone, toISOString() is using standard timezone.

York Chen
  • 744
  • 4
  • 9
  • It depends on what result do you want. If you need ISO String, that is correct. If you need local result, just use toString(), or do the format by yourself. – York Chen Nov 11 '20 at 06:08
0

I have searched and I find best solution for every date object to convert in any format. Comment if you agree?

var dateObj = {
  day:2,
  month:5,
  year:2012
}
var date = new Date;
date.setFullYear(dateObj.year,dateObj.month-1,dateObj.day)
console.log(date)