Why is Convert.ToDateTime () not working in this example?

I am trying to use both System.DateTime.Now.ToString () and Convert.ToDateTime and have come across some weird behavior. I narrowed the problem down to Convert.ToDateTime. For some reason, the DateTime type set to System.DateTime.Now does not match the one that was converted from a string. However, when outputting any of them, they appear to be the same.

(I tried using Trim (), TrimStart (), and TrimEnd () to no avail.)

This is the result in the console after running this in unity: 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()));
    }
}
+4
source share
3 answers

, DateTime DateTime.ToString().

, :

DateTime convertedTime =
    new DateTime(
        saveTime.Year,
        saveTime.Month,
        saveTime.Day,
        saveTime.Hour,
        saveTime.Minute,
        saveTime.Second,
        saveTime.Millisecond);

DateTime, .

, DateTime ( 12:00 , 1 0001 ). . Ticks , DateTime .

, DateTime, :

DateTime convertedTime = new DateTime(saveTime.Ticks);

, ( ), :

string store = saveTime.Ticks.ToString();

DateTime convertedTime = new DateTime(Convert.ToInt64(store));
+8

DateTime.ToString() . DateTime, , .

var dateWithMilliseconds = new DateTime(2016, 1, 4, 1, 0, 0, 100);  
int beforeConversion = dateWithMilliseconds.Millisecond;  // 100

var dateAsString = dateWithMilliseconds.ToString();       // 04-01-16 1:00:00 AM (or similar, depends on culture)
var dateFromString = Convert.ToDateTime(dateAsString);
int afterConversion = dateFromString.Millisecond;         // 0
+3

I think you are losing your time zone during the method ToString(). Thus, the re-converted DateTimeends in a different time zone.

Check also the property DateTime.Kind.

+1
source

Source: https://habr.com/ru/post/1622660/


All Articles