Ganbin
Ganbin

Reputation: 2072

Need help on converting a time to date using momentjs

I'm using an input type="time" and I want to convert my time with a timestamp of 0. It mean that I want my date to look like Thu Jan 01 1970 02:35:00 GMT+0000.

If I write let value = moment('02:35','HH:mm').utc() I get Mon Oct 31 2016 01:35:00 GMT+0000. Is there a way to get the time with a timestamp starting at 0without to specified the yearthe monthand the day?

I specify again that my case is working with a input type="time" and that I only get the value in this format HH:mm

Here is a gist to play around.

Upvotes: 0

Views: 44

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

You can parse the date relative to January 1st, 1970.

var time = document.getElementById('time-input').value;
var date = moment.utc(time + ' 1/1/1970','HH:mm D/M/YYYY').format('ddd MMM DD YYYY HH:mm:ss zZ');

console.log(date); // Thu Jan 01 1970 02:35:00 UTC+00:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<input id="time-input" type="time" value="02:35" />

Upvotes: 2

DBS
DBS

Reputation: 9994

I may be misunderstanding, but to use Unix time 0 as the base for your time, you can get Unix time then edit the elements of the time you wish to change:

let value = moment(0).set({'hour': 2, 'minute': 35}).utc();

moment(0) will get the start date (Start of Unix time), then .set({'hour': 2, 'minute': 35}) will allow you to edit the time.

This will return: Thu Jan 01 1970 02:35:00 GMT+0000

Upvotes: 3

Related Questions