更新JavaScript对象的日期部分,而无需更改时间部分 [英] Updating the date portion of a javascript object without changing the time portion

查看:106
本文介绍了更新JavaScript对象的日期部分,而无需更改时间部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript的最佳方式是设置JavaScript日期对象的日期部分而不影响时间部分?

What is the best way in JavaScript to set the date portion of a JavaScript date object without affecting the time portion?

让我们说你有一个这样的日期
Wed Oct 31 2012 10:15:00 GMT-0400(EDT)

Lets say you have a date like this Wed Oct 31 2012 10:15:00 GMT-0400 (EDT)

你想更新它是11月1日,而不改变时间。

And you want to update it to be November 1st without changing the time.

乍一看,你会认为这将工作,

At first glance, you'd think this would work,

exampledate.setFullYear(2012);
exampledate.setMonth(10);
exampledate.setDate(1);

但结果是
Sat Dec 01 2012 10:15 :00 GMT-0500(EST)

我认为这个原因是10月份有31天,11月刚刚30岁。所有的时间都不行。我的其他选择是什么?我必须创建一个新的日期对象吗?

I think reason for this is that October has 31 days and November has just 30. Since this obviously doesn't work right all the time. What are my other options? Will I have to create a new date object?

推荐答案

JavaScript日期对象设置器方法通常允许您(可选)设置多个日期/时间组件一次(除主要组件之外),适合情况---这是你想要做的。

JavaScript Date object setter methods often allow you to (optionally) set multiple date/time components all at once (in addition to the primary component), as appropriate for the situation --- this is what you want to do.

对于您的用例, setFullYear 的语法为 setFullYear(年,月,天),所以除了明确设置年份(这将导致月和日期根据您的初始日期被隐式更新),您还可以明确地设置月份和日期,而您在它。例如:

For your use case, the syntax for setFullYear is setFullYear(year,month,day), so in addition to explicitly setting the year (which would cause the month and date to be implicitly updated based on your initial date), you could also explicitly set the month and day while you're at it. For instance:

var d = new Date();
d.setFullYear(2020,10,3);

将返回

Tue Nov 03 2020 13:10:34 GMT-0500 (EST)

查看 JavaScript setFullYear()方法获取更多详细信息。

See the JavaScript setFullYear() method for more details.

由于Date对象的时间组件(例如,小时,分钟,秒,毫秒)不依赖于日期部分(年,月,日),您的初始时间组件将被维护。如果您需要更新时间组件,则可以根据需要安全地使用 setHours()或其他方法,因为不会对日期组件进行隐式更新。

Because the time components of the Date object (e.g. hours, minutes, seconds, milliseconds) are not dependent on the date portions (year,month,date), your initial time components will be maintained. If you need to then update the time components, you can safely use setHours() or other methods as needed, because no implicit updates to the date components will occur.

这篇关于更新JavaScript对象的日期部分,而无需更改时间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆