如何更改DateTime变量的时间? [英] How do I change a DateTime variable's time?

查看:41
本文介绍了如何更改DateTime变量的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DateTime的新手和google真诚地使我失望.我目前正在使用DateTime变量来跟踪游戏中的时间.

New to DateTime and google is sincerely failing me. I'm currently using a DateTime variable to track time in my game.

问题是,任何更改所述DateTime的尝试都会导致属性[时间]为只读"错误.任何帮助,可行的替代方案或环形交叉路口都将不胜感激.

The problem is, is that any attempt of changing said DateTime is resulting in a "Property [time] is ReadOnly" error. Any help, working alternatives or roundabouts would be appreciated.

Sub IncreaseTime(unit As Integer)
    Dim NewDate As DateTime

    With World.WorldTime
        NewDate = New DateTime(.Date.Year, .Date.Month, .Date.Day, .Date.Hour, .Date.Minute, .Date.Second + unit)
        .Date = NewDate
    End With
End Sub

编辑#1;

   Sub IncreaseTime(unit As Integer)
    Dim NewDate As DateTime

    With World.WorldTime
        NewDate = NewDate.AddSeconds(unit)
        .Date = NewDate
    End With
End Sub

编辑#2;

推荐答案

DateTime 类型为不可变-所有属性均为只读,因此您无法设置 Date Time 或其中的一部分(年份,分钟等).

The DateTimetype is immutable - all the properties are read-only, so you cannot set the Date, Time or even a part of them (years, mins etc).

由于无法直接设置任何属性,因此要更改其中的任何一部分,请使用其中一种方法来更改 AddSeconds() AddYears()等.创建并返回具有所需调整的新 DateTime 值.要减去,只需使用一个负值:

Since none of the properties can be set directly, to change any part of one use one of the methods to AddSeconds(), AddYears() etc. These all create and return a new DateTime value with the desired adjustment. To subtract, just use a negative value:

WorldDate = WorldDate.AddMinutes(unit)
' to subtract:
WorldDate = WorldDate.AddMinutes(-unit)

必须将结果 分配给新变量或现有变量.

The result must be assigned, either to a new variable or the existing one.

原因非常简单:添加n分钟可能会跨越 Day Month 以及 DayOfYear之类的其他属性 DayOfWeek .允许直接访问将需要大量检查值的合法性(例如 .Minutes = 67 .Day = 33 ).

The reason is pretty simple: adding n minutes might roll over the Day or Month as well as other properties like DayOfYear or DayOfWeek. Allowing direct access would require lots of checking that the value is legal (like .Minutes = 67 or .Day = 33).

要将日期或时间设置为特定值,请使用一些旧值创建一个新的日期或时间,并指定所需的其他值:

To set the date or time to specific values, create a new one using some of the old values and specifying the other values you want:

WorldDate  = New DateTime(WorldDate.Year, WorldDate.Month, WorldDate.Day, 
         myHrs, mySecs, myMins)

这篇关于如何更改DateTime变量的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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