rselvaganesh
rselvaganesh

Reputation: 1122

How to get date & time using moment.js

I need to get the start date and end date in the below format using moment js

startDate = 20160427000000 and endDate = 20160427235959

Here the start date appended with 000000 and end date appended with 235959

What is the right way to get this result in javascript

Upvotes: 1

Views: 14157

Answers (3)

Pawan Kumar
Pawan Kumar

Reputation: 11

For Getting Format Like these in moment.js - (2020-12-15T13:00:00)

let a =2023-01-14T20:15:00-05:00

You can use moment(a).format("YYYY-MM-DDTHH:mm:ss")

Result: 2023-01-14T20:15:00

Upvotes: 1

RobG
RobG

Reputation: 147553

I'm totally confused, I don't know if you want to parse the format or output it. If you want to parse dates using moment.js in that format, then in time zone +05:30:

// Format YYYYMMDDHHmmss for 2016-04-26T00:00:00
var s = '20160426000000';
var x = moment(s, 'YYYYMMDDHHmmss');

// Show date in ISO 8601 extended format
console.log(x.format()); // 2016-04-26T00:00:00+05:30

To shift to the end of the day and output in YYYMMDDHHmmss format:

console.log(x.endOf('day').format('YYYYMMDDHHmmss')); // 20160426235959

In the format string:

  • YYYY is 4 digit year
  • MM is two digit month
  • DD is two digit day
  • HH is two digit hour in 24 hour format
  • mm is two digit minute
  • ss is two digit seconds

Upvotes: 0

Ben
Ben

Reputation: 631

You want the format operator. Since it looks like your 0's and 2359's are hardcoded (I assume you're doing start and end of days), try:

startDate = moment().format('YMMDD000000');
endDate = moment().format('YMMDD235959');

EDIT: Or, as RobG pointed out, you can use:

startDate = moment().startOf('day').format("YMMDDHHmmss");
endDate = moment().endOf('day').format("YMMDDHHmmss");

(Which is much neater)

Upvotes: 2

Related Questions