Waf*_*fer 4 c# datetime unity-game-engine
我正在尝试使用System.DateTime.Now.ToString()和Convert.ToDateTime,并遇到了一些奇怪的行为.我已将问题缩小到Convert.ToDateTime.由于某种原因,使用System.DateTime.Now设置的DateTime类型与从字符串转换的DateTime类型不同.但是,当您输出其中任何一个时,它们看起来是相同的.
(我尝试使用Trim(),TrimStart()和TrimEnd()无济于事.)
在统一运行之后,这是控制台中的输出:http: //imgur.com/1ZIdPH4
using UnityEngine;
using System;
public class DateTimeTest : MonoBehaviour {
void Start () {
//Save current time as a DateTime type
DateTime saveTime = System.DateTime.Now;
//Save above DateTime as a string
string store = saveTime.ToString();
//Convert it back to a DateTime type
DateTime convertedTime = Convert.ToDateTime(store);
//Output both DateTimes
Debug.Log(saveTime + "\n" + convertedTime);
//Output whether or not they match.
if (saveTime == convertedTime)
Debug.Log("Match: Yes");
else
Debug.Log("Match: No");
//Output both DateTimes converted to binary.
Debug.Log(saveTime.ToBinary() + "\n" + (convertedTime.ToBinary()));
}
}
Run Code Online (Sandbox Code Playgroud)
当你通过转换DateTime为字符串时,你会失去很多DateTime.ToString().
即使你包括这样的毫秒:
DateTime convertedTime =
new DateTime(
saveTime.Year,
saveTime.Month,
saveTime.Day,
saveTime.Hour,
saveTime.Minute,
saveTime.Second,
saveTime.Millisecond);
Run Code Online (Sandbox Code Playgroud)
你仍然会得到一个不同于DateTime原来的不同.
其原因在于内部DateTime存储了多个刻度(从0001年1月1日午夜12:00起).每个刻度表示一千万分之一秒.您需要获得相同数量的Ticks才能使两个DateTime对象相等.
所以,为了获得平等DateTime,你需要这样做:
DateTime convertedTime = new DateTime(saveTime.Ticks);
Run Code Online (Sandbox Code Playgroud)
或者,如果要将其转换为字符串(存储它),可以将刻度存储为如下字符串:
string store = saveTime.Ticks.ToString();
DateTime convertedTime = new DateTime(Convert.ToInt64(store));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
889 次 |
| 最近记录: |