在moment.js中,是否可以具有日期时间字符串并保留日期但更改时间? [英] In moment.js, is it possible to have a date-time string and keep the date but change the time?
问题描述
我正在使用moment.js,并希望使用新的用户输入时间来更新日期时间字符串.日期没有改变,只有时间.时区没有变化,只是小时和分钟值可能已更改.
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?
这是我期望的:
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'
推荐答案
如果将用户输入的时间格式设置为13:00
,则可以执行以下操作:
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()
)
使用 https://momentjs.com/docs/#/get-set /hour/和 https://momentjs.com/docs/# /get-set/minute/
如果它是用PM和AM系统格式化的,则可以使用相同的格式,但要进行更多的分析,才能知道它是5.00 AM还是PM.
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.
这篇关于在moment.js中,是否可以具有日期时间字符串并保留日期但更改时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!