简体   繁体   中英

How to deduct time in 24 hours using moment

My use case is very simple, How do i deduct the current time in 24 hours. Technically it is like snapchat, 24 hours from now it will dissapear, hence why I need to deduct the time.

11:50 PM - 10 Jan 2017

I want to deduct the current time to the next 24 hours time only

(10:50 PM - 11 Jan 2017) - (11:50 PM 10 Jan 2017) = 1 hour left

How would I do such thing in Moment.js ?

You can add -24 hours. See moment.add

moment(date).add(-24, 'hours');

And to display relative time you can use moment.fromNow

Yes you should use moment.js take a look here

Moment from method

In fact you can deduct time passed between to dates like this

var start = moment("10:50 PM - 11 Jan 2017");
var end = moment("11:50 PM 10 Jan 2017");
start.from(end); // "1 hour"

I think this would help you :

//valid formats to subtract

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

//easy examples

var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()

Read http://momentjs.com/docs/#/parsing/ for documentation on moment js parse.

This just might work. It did work in JSFiddle http://jsfiddle.net/Bjolja/p2bcm2oa/

var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM