简体   繁体   中英

DateTime conversion not working c#

EDIT I have completely edited the code, since a lot of my strange attempts at fixing the basic error were misleading people to believe there were errors in my code, when it was simply trying any and all apprches to solving the problem. The many myriad of ways I have attempted to convert a perfectly valid, BUILT IN date time format to system datetime object has failed, and don't know why.

endedit

I need help, I have literally just ripped some hair out as a result of being unable to solve such a seemingly simple task, trying to convert my date log (a csv, which is reading correctly) to DateTime. the error is in trying to convert my log entries (which when printed, are correctly formatted date times) to DateTime Objects for comparison.

EXAMPLE INPUT FROM CSV: 2016-03-22T04:03:31
EXAMPLE INPUT FROM File.GetLastWriteUTC(path): 2016-03-22T04:03:27

Both are identical, but I can't convert my csv log entries to DateTime for no particular reason.

I have tried any number of formats. I am writing to the console which proves that the dates that I am working with are indeed correct C# compatible date time formats. I have tried DateTime.Parse/ParseExact with every parameter I can find online. I am even trying to remap a new date time to a new format, or converting the string, to date time, back to string with a format, and converting that PROPERLY FORMATTED STRING back to a date time.

And yet, every time I run my program, I'm left with "When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object." And "Make sure your arguments are in the same format", though I have PROVEN that they are beyond a shadow of a doubt the correct format, no missing zero's, and no single quotations. I'm writing out built in formats using the .ToString modifiers, I have went down the list trying f, F o, O, s, S, etc.

Someone please save my sanity. Below you can see a number of my brain fried hackish attempts to figure out why this isn't working, and just when I think I've come up with something clever, GUARANTEEING the correct format, it still fails.

        using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace vimbackupscript2
{
    class Program
    {
        static void Main()
        {
            while (true)
            {
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = "C:\\Program Files\\Git\\etc";
                watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.LastWrite;
                DateTime time = File.GetLastWriteTimeUtc(watcher.Path + "\\vimrc");
                string logPath = "C:\\Users\\USERPROFILE\\vimbackup\\log.csv";
                var logFile = File.ReadAllText(logPath).Split(',');

                foreach (var log in logFile)
                {
                    Console.WriteLine(Convert.ToDateTime(log));

                }

                watcher.Changed += new FileSystemEventHandler(OnChanged);

                watcher.WaitForChanged(WatcherChangeTypes.All);

                File.WriteAllText(logPath, time.ToString("s") + ",");
            }

        }


    }

}

You can use DateTime.ParseExact("2016-03-22T04:03:31", "yyyy'-'MM'-'dd'T'HH':'mm':'ss") to get the proper DateTime in any culture settings.

There are other issues in your code though. What do you think you can get by converting to datetime, then to string and then to datetime?

If only the comparison fails, clearly the datetime conversion works since you get that far.

You're taking a DateTime in UTC , then creating another one based on that in local time, so it'll be off based on the timezone offset. Then you do a ToString() which does nothing.

So is your actual issue that you mess up DateTime with timezones? Debugger will show easily what the times are.

If you want to compare the DateTimes in local timezone, use GetLastWriteTime to get the time.

The issue is if you debug the code and examine the number of ticks. The best solution would be to create a DateTime type in your foreach loop and then compare. i,e var result = new DateTime(...) . Ive also posted my test code

在此处输入图片说明

using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main()
        {
            {
                //I NEED TO COMPARE THIS TIME WITH THE LAST LOGGED TIME
                DateTime x = DateTime.Now;
                DateTime time = x; //File.GetLastWriteTimeUtc(watcher.Path + "\\vimrc");
                DateTime newTimeFormat = new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
                time.ToString("O");

                string log = x.ToString();
                {

                    Console.WriteLine(Convert.ToDateTime(log).ToString("s"));
                    var result = Convert.ToDateTime(Convert.ToDateTime(log).ToString("s"));

                    //THIS ERRORS EVERY SINGLE TIME, EVEN WHEN LOG IS CONVERTED TO A 100% VERIFIABLE LEGITIMATE FORMAT
                    if (result < time)
                    {
                        Console.WriteLine("bleh why don't my conversions work!?!??!!?");
                    }
                }
            }

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM