0

json returns years in this format

"dateOfBirth":"1997-03-23T08:00Z"

I need to convert the years to this format

var bDate = "3/23/1997";
var bDateformat = new Date(bDate).getTime() / 1000 | 0;
console.log("Birthday: "+bDateformat);

so in example i get returned value of

859093200
MShack
  • 642
  • 1
  • 14
  • 33
  • 1
    What's the actual question? – Alicia Sykes May 05 '22 at 12:46
  • If it's how to convert seconds into years, then just: `Math.floor(bDateformat / 31557600)` – Alicia Sykes May 05 '22 at 12:47
  • The `Date` constructor understands the format `YYYY-MM-DD` as well, so just cut off the `T08:00Z` part from your input date ...? (It would understand the full `1997-03-23T08:00Z` as well, but if you are passing in a specific time as well, your result in seconds will of course slightly differ.) – CBroe May 05 '22 at 12:47
  • ok , thanks , how can i trim off the part not needed ? – MShack May 05 '22 at 12:49
  • `var bDate = "3/23/1997";` -> Read [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/q/51715259) – VLAZ May 05 '22 at 12:53

2 Answers2

1

You can use this to output in JSON format:

var bDate = "3/23/1997";

new Date(bDate ).toJSON()
// result: '1997-03-22T19:30:00.000Z'

Or you can use this to get the date object from the JSON string:

var bDate = '1997-03-22T19:30:00.000Z';

new Date(bDate).toLocaleString()
// result: '3/23/1997, 12:00:00 AM'
Joseph Didion
  • 142
  • 1
  • 6
itsalir
  • 26
  • 3
0

This was also my question before, I have easily overcome this by using the Moment.js. It is easy to use and very understandable. Also, you can easily convert the patterns all together very simply.

Documentation on Moment.js

I don't know if your project is HTML and Javascript (or you are using node or ...), you can simply download (or install the package) the Moment.js and after including it in your project, the only thing you need to do is:

var bDate = "1997-03-23T08:00Z"
var newBDate = moment(bDate, "YYYY-MM-DDTHH:mm[Z]").format('M/DD/YYYY');
//Or you can use any other final date format as you want
console.log(newBDate)

This will help users to easily convert to any time format they want.

Shayan Faghani
  • 243
  • 1
  • 9