How to return the current timestamp with Moment.js

2019-02-01 03:41发布

问题:

Folks,

I am trying to understand the MomentJS API. What is the appropriate way to get the current time on the machine?

var CurrentDate = moment();

vs

var CurrentDate = moment().format();

Trying to parse their docs, and its not apparent what to use.

http://momentjs.com/docs/#/query/is-a-moment/

回答1:

Here you are assigning an instance of momentjs to CurrentDate:

var CurrentDate = moment();

Here just a string, the result from default formatting of a momentjs instance:

var CurrentDate = moment().format();

And here the number of seconds since january of... well, unix timestamp:

var CurrentDate = moment().unix();

And here another string as ISO 8601 (What's the difference between ISO 8601 and RFC 3339 Date Formats?):

var CurrentDate = moment().toISOString();

And this can be done too:

var a = moment();
var b = moment(a.toISOString());

console.log(a.isSame(b)); // true


回答2:

moment().unix() you will get a unix timestamp

moment().valueOf() you will get a full timestamp



回答3:

Still, no answer. Moment.js - Can do anything but such a simple task.

I'm using this:

moment().toDate().getTime()


回答4:

Try to use it this way:

var current_time = new moment().format("HH:mm");


回答5:

If you just want the milliseconds since 01-JAN-1970, then you can use

var theMoment = moment(); // or whatever your moment instance is
var millis;

millis = +theMoment; // a short but not very readable form
// or
millis = theMoment.valueOf();
// or (almost sure not as efficient as above)
millis = theMoment.toDate().getTime();


回答6:

Try this

console.log(moment().format("MM ddd, YYYY hh:mm:ss a"));

console.log(moment().format("MM ddd, YYYY hh:mm:ss a"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>



回答7:

Try this way:

console.log(moment().format('L'));
moment().format('L');    // 05/25/2018
moment().format('l');    // 5/25/2018

Format Dates:

moment().format('MMMM Do YYYY, h:mm:ss a'); // May 25th 2018, 2:02:13 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY");               // May 25th 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                          // 2018-05-25T14:02:13-05:00

Visit: https://momentjs.com/ for more info.



回答8:

Get by Location:

moment.locale('pt-br')
return moment().format('DD/MM/YYYY HH:mm:ss')