在日期时间字段中设置更新时间部分,但不更新日期部分

sethours updating time part but not the date part in date time field

本文关键字:更新 日期部 日期 时间部 字段 设置 时间      更新时间:2023-09-26

我有一个datetime字段,只有日期作为格式。此外,我还在onload时添加了一个脚本,以便在访问记录时将12:00添加到该字段。它按预期工作,并增加了12个小时的时间部分。但是它没有相应地更新日期。

例如,I've Date Become Manager字段,其值为'Thu Apr 30 23:00:00 UTC-1200 1992'。在添加12小时后,它将时间部分更新为'Thu Apr 30 12:00:00 UTC-1200 1992',但不添加任何内容到其日期。下面是我要更新的代码片段。

    function updateFields(field){
    var dateField = Xrm.Page.getAttribute(field);
    if(dateField.getValue()== null)
    {
        dateField.setValue(new Date());
    }
    dateField.setValue(dateField.getValue().setHours(12, 0, 0));
}

如果我做错了什么请告诉我

setHours只有改变的时间,它不计算任何东西

执行这种计算的最常见的方法是:
var numberOfHours = 12; // how many hours you want to add. Can be *negative* too.
var millisecondsInAnHour = 60 * 60 * 1000; // this is constant
var offset = numberOfHours * millisecondsInAnHour;
var newFieldValue = dateField.getValue().getTime() + offset;
dateField.setValue(newFieldValue);

基本上,您获取值的时间并为其添加/减去毫秒数

所以为了清楚,您想要在当前日期值上添加12小时,(而不是将时间元素设置为12:00)?

setHours只是设置时间,它不会在时间上增加12小时。如果你做多次,它将永远是12小时,而不是0 - 12 - 24。

如果你把setHoursgetHours结合起来,你应该能够达到预期的行为。

var d1 = new Date();
console.log("Original Date: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Once: " + d1);
d1.setHours(12);
console.log("Set 12 Hours Twice: " + d1);
var d2 = new Date();
console.log("Original Date 2: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Once: " + d2);
d2.setHours(d2.getHours() + 12);
console.log("Add 12 Hours Twice: " + d2);
输出:

Original Date: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Once: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Set 12 Hours Twice: Tue Sep 22 2015 12:45:39 GMT+0100 (GMT Daylight Time)
Original Date 2: Tue Sep 22 2015 09:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Once: Tue Sep 22 2015 21:45:39 GMT+0100 (GMT Daylight Time)
Add 12 Hours Twice: Wed Sep 23 2015 09:45:39 GMT+0100 (GMT Daylight Time)

我刚刚更新了我的代码,它的工作。请看下面的代码片段:

function updateFields(field){
var dateField = Xrm.Page.getAttribute(field);
if(dateField.getValue()== null)
{
    dateField.setValue(new Date());
}
dateField.setValue(dateField.getValue().setHours(dateField.getValue().getHours() + 12));}