How to convert unix timestamp to calendar date moment.js
Asked Answered
V

16

211

I have a unix timestamp, and I'm trying to convert it into a calendar date such as MM/DD/YYYY. So far, I have this:

$(document).ready(function() {
  var value = $("#unixtime").val(); //this retrieves the unix timestamp
  var dateString = moment(value).calendar(); 
  alert(dateString);
});

When I try to print out the calendar date, the window says "Invalid date". Can anyone help me out?

Vuong answered 6/1, 2014 at 4:38 Comment(0)
C
538

Using moment.js as you asked, there is a unix method that accepts unix timestamps in seconds:

var dateString = moment.unix(value).format("MM/DD/YYYY");
Conchiferous answered 6/1, 2014 at 5:16 Comment(9)
That's not a calendar date.Philemon
@IanWarburton - it's not??Conchiferous
I suppose it is according to the question. But I think a calendar date in moment.js looks like this.... moment(new Date(item.date)).calendar()Philemon
@IanWarburton - You wouldn't need the new date object in there. The calendar function is nice (docs here), but not in the format that the OP asked for.Conchiferous
This is correct answer, you can also convert your unix timestamp to date to check with this tool that's using moment js epochconvert.comGalligan
Does this have timezone included?Trichloroethylene
@M98 - this returns the date converted to the local time zone. If you want UTC or a specific time zone, use .utc() or .tz(...).Conchiferous
It's worth noting why the question fails but this works. The reason is because monent(number) expects a unix timestamp in milliseconds (which is consistent with the Date object), whereas the unix timestamp is in seconds by default. So you could also do moment(value*1000) instead of moment.unix(value), but using unix is clearer.Intolerant
in my case const dateStringToDisplay = moment(new Date(timestamp)).format("DD-MM-YYYY HH:mm:ss");Nevski
R
48

UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:

var date = new Date(unixTimestamp*1000);
Rollie answered 6/1, 2014 at 4:40 Comment(2)
Yes, that was the solution with the latest version of moment, or at least the one i got from npm recently. even though i got the .unix() from moment i had to * 1000 when instantiating it again. for instance: moment( moment().unix() * 1000 )Peptic
Best answer comparing to moment.js logicGratifying
T
34

Moment.js provides Localized formats which can be used.

Here is an example:

const moment = require('moment');

const timestamp = 1519482900000;
const formatted = moment(timestamp).format('L');

console.log(formatted); // "02/24/2018"
Tala answered 24/2, 2018 at 14:40 Comment(1)
"Fecha inválida" withe the example you providedErmin
F
14

Only it,

moment.unix(date).toDate();
Fertile answered 23/5, 2019 at 21:31 Comment(0)
B
13

Might be a little late but for new issues like this I use this code:

moment(timestamp, 'X').format('lll');

You can change the format to match your needs and also add timezone like this:

moment(timestamp, 'X').tz(timezone).format('lll');

Ref: https://momentjs.com/docs/#/parsing/string/

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

example

moment('2022-12-03').format('YYYY-MM-DD'); //avoid use this because inconsistentcy
moment('2022-12-03','YYYY-MM-DD').format('YYYY-MM-DD'); //use this instead
moment('1670000400','X').format('YYYY-MM-DD'); //use this instead (timestamp)
moment('03-2022-12','DD-YYYY-MM').format('YYYY-MM-DD'); //UNCOMMON CASE
Brasil answered 26/2, 2019 at 13:28 Comment(2)
This is the best method I've seen here.Kalmia
Just to add to this answer (which is the most correct answer on here). Use lowercase x for ms unix timestamp. Documentation hereElectrometer
C
5
new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()
Cochleate answered 1/7, 2015 at 13:25 Comment(1)
While this code may answer the question, it would be better to include some context, explain how it works, and describe when to use it. Code-only answers are not useful in the long run. Additionally, your code is not properly formatted.Glick
L
5
moment(1454521239279).toDate()
moment(1454521239279).format()
Lissalissak answered 6/6, 2020 at 23:3 Comment(0)
F
2

I had a timestamp like 1668919452.

Doing this got me the proper result : {moment.unix(created).format("l")}

I added the .unix method.

Before that, the time stamps were registered as 1970s

Feces answered 28/11, 2022 at 14:23 Comment(0)
K
1
$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment(value, 'MM/DD/YYYY', false).calendar(); 
    alert(dateString);
});

There is a strict mode and a Forgiving mode.

While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.

In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.

A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.

In strict mode, the following code results in 'Invalid Date' being displayed:

moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"

In forgiving mode using a format string, you get a wrong date:

moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"

another way would be

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment.unix(value).calendar(); 
    alert(dateString);
});

Kikelia answered 5/4, 2019 at 17:45 Comment(0)
S
1

This function creates date from timestamp:

    function formatDateTime(dateString) {
        const parsed = moment(new Date(dateString))

        if (!parsed.isValid()) {
            return dateString
        }

        return parsed.format('MMM D, YYYY, HH:mmA')
    }
Sidell answered 5/8, 2019 at 18:15 Comment(0)
F
1

First you can convert timestamp to date object with js

const date = new Date(timestamp)

Then you can use momentjs to format it the way you want

const formatDate = moment(date).format("DD/MM/YYYY")

Furlani answered 24/11, 2022 at 11:1 Comment(1)
Welcome to stackoverflow. This question is asked more than 8 years ago and it has an accepted answer. Please add some details about the reason you are adding a new answerWoodrowwoodruff
N
0

I fixed it like this example.

$scope.myCalendar = new Date(myUnixDate*1000);
<input date-time ng-model="myCalendar" format="DD/MM/YYYY" />
Norland answered 6/11, 2018 at 16:52 Comment(0)
T
0
moment(timestamp).format('''any format''')
Trundle answered 9/6, 2020 at 15:54 Comment(2)
While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.Cacodyl
Sure, will keep this in mind for future answers @CacodylTrundle
L
0

Using: moment.unix(timeSpan).format(DD/MM/YYYY')

Leger answered 24/4, 2023 at 9:2 Comment(0)
J
0

Leaving this here since I didn't find a specific answer to my particular situation.

The timestamp I was trying to format was 1676665996075, but I had it stored in a property as a string value, so it was actually "1676665996075".

I tried doing moment.unix(property.value) but I kept getting Wed Nov 07 55100 10:50:21 GMT-0300. As you can see, the date was coming out all wrong.

It worked fine when I started transforming it into a number first, and didn't even need to call .unix().

moment(Number(property.value)) did the trick for me. It came out as Fri Feb 17 2023 12:28:11 GMT-0300.

So, remember that the timestamp value needs to be a number.

Justly answered 28/7, 2023 at 17:58 Comment(0)
D
0

I tried multiple times to use the unix method but it doesn't work properly. the one that worked fine is convert the unix timestamp to Number and then use the normal moment like moment(Number(value))

Des answered 19/9, 2023 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.