Home > other >  Convert timestamp to "YY/MM/DD" with JS
Convert timestamp to "YY/MM/DD" with JS

Time:05-18

I need to convert my "80814.89999999851" timestamp to a YY/MM/DD string. I started by doing this:

var prova = info.originalEvent.timeStamp; //this path lead to: 80814.89999999851

var prova2 = new Date(prova);

Now I have it as a datetime (if i'm not mistaken) but i don't know how to keep just the year/month/day and then convert it to a string. Can someone help me?

CodePudding user response:

You're almost there. One way to do it would be like this:

var unixTimestamp = 1652783393 // time since Jan 1st 1970 in seconds
var date = new Date(unixTimestamp * 1000); // it takes milliseconds

var datestring = date.getFullYear()   "-"   (date.getMonth()   1)   "-"   date.getDate()
console.log("Date: "   datestring)

This prints out:

Date: 2022-5-17

Notice the 1 added to getMonth. This is because the months go from 0 - 11.

I noticed your timestamp only has 5 digits. There might be something wrong with that timestamp, since it doesn't look plausible as either seconds or milliseconds.

For more information you could refer to this article I found: https://coderrocketfuel.com/article/convert-a-unix-timestamp-to-a-date-in-vanilla-javascript

CodePudding user response:

This timestamp is not seconds since unix epoch, its seconds since timeOrigin (most likely time since page was loaded), to convert it to date you need to obtain timeOrigin first. Take a look at this question: Knowing the time origin of event's timestamp.

https://developer.mozilla.org/en-US/docs/Web/API/Event/timeStamp

CodePudding user response:

First convert your time to DateTime as it is in seconds right now

var date = new DateTime(Convert.ToInt64(80814.89999999851));

And then convert to the format you need using the ToString() method

var temp = date.ToString("yy/MM/dd");

I think this will help you.

  • Related