简体   繁体   English

日期时间转换不起作用C#

[英]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. 我需要帮助,由于无法解决如此看似简单的任务,我实际上只是扯掉了一些头发,试图将我的日期日志(正确读取的csv)转换为DateTime。 the error is in trying to convert my log entries (which when printed, are correctly formatted date times) to DateTime Objects for comparison. 错误是试图将我的日志条目(在打印时,格式正确的日期时间)转换为DateTime对象以进行比较。

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. 两者是相同的,但是我没有特殊原因无法将我的csv日志条目转换为DateTime

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. 我正在写一个控制台,该控制台证明我正在使用的日期确实是正确的C#兼容日期时间格式。 I have tried DateTime.Parse/ParseExact with every parameter I can find online. 我已经尝试过使用我可以在线找到的每个参数的DateTime.Parse / ParseExact。 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." 但是,每次运行程序时,我都会看到“将字符串转换为DateTime时,在将每个变量放入DateTime对象之前,分析字符串以获取日期”。 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. 我正在编写使用.ToString修饰符的内置格式,我在尝试f,F o,O,s,S等的列表中处于下降位置。

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. 您可以使用DateTime.ParseExact("2016-03-22T04:03:31", "yyyy'-'MM'-'dd'T'HH':'mm':'ss")来获取正确的DateTime文化设置。

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. 您正在UTC中获取一个DateTime,然后根据本地时间创建另一个DateTime,因此它将根据时区偏移量关闭。 Then you do a ToString() which does nothing. 然后,您执行不执行任何操作的ToString()

So is your actual issue that you mess up DateTime with timezones? 那么,您的实际问题是使DateTime与时区搞混了吗? Debugger will show easily what the times are. 调试器将轻松显示当前时间。

If you want to compare the DateTimes in local timezone, use GetLastWriteTime to get the time. 如果要比较本地时区中的DateTime,请使用GetLastWriteTime来获取时间。

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. 最好的解决方案是在foreach循环中创建DateTime类型,然后进行比较。 i,e var result = new DateTime(...) . i,e var result = new DateTime(...) Ive also posted my test code Ive还发布了我的测试代码

在此处输入图片说明

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!?!??!!?");
                    }
                }
            }

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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