In moment.js, is it possible to have a date-time s

2019-12-16 17:56发布

I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.

How would I take a string like this and convert it such that the time is different?

This is would I'd expect:

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'

3条回答
Luminary・发光体
2楼-- · 2019-12-16 18:16

If the user-entered time is formatted as such 13:00 you could do :

   const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
var userInput = "13:20"
    const newDateTimeString = (
        moment(dateTimeString)
        .hours(userInput.split(":")[0])
        .minutes(userInput.split(":")[1])
        .format()
    )

Using https://momentjs.com/docs/#/get-set/hour/ and https://momentjs.com/docs/#/get-set/minute/

If it's formatted with PM and AM system, you could to the same, but with a little bit more of parsing, to know if it's 5.00 AM or PM.

查看更多
我想做一个坏孩纸
3楼-- · 2019-12-16 18:17

There is no built in function like changeTime, you can write your own using set.

You can add changeTime using moment.fn

The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.

You can create a temp moment object with your "time to add" value using moment(String, String), then use set(Object(String, Int)) and getters like hours() and minutes().

Here a live sample:

moment.fn.changeTime = function(timeString) {
  let m1 = moment(timeString, 'hh:mm A');
  return this.set({h: m1.hours(), m: m1.minutes()});
}

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)

console.log(newDateTimeString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>

查看更多
Root(大扎)
4楼-- · 2019-12-16 18:27

One possible way is to use moment to grab the date and then combine it with your custom time value in another moment() call like so:

const newDateTimeString = (
    moment(`${moment(dateTimeString).format('YYYY-MM-DD')} 05:20 PM`)
    .format()
)
查看更多
登录 后发表回答