Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - In moment.js, is it possible to have a date-time string and keep the date but change the time?

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...