0

I have a XML file with these datetime. Is it possible to get the time difference between the latest time with the previous time?

Ex: In this pic, latest time is 10/27/2021 09:15, previous time is 10/26/2021 16:52, so I want to get the difference in these two times and run something behind the time difference if the time difference more than 2 hours. Picture 1

while, this time, latest time become 10/27/2021 10:32, previous time is 10/27/2021 09:15, I need to compare with these two this time. If the time difference is not more than 2 hours, then do nothing. Picture 2

I had try and save the datetime in the XML file.

        string xmlFilePath = Directory.GetCurrentDirectory() + @"\database.xml";
        XDocument doc;
        try
        {
            doc = XDocument.Load(xmlFilePath);
        }
        catch
        {
            doc = new XDocument(new XElement("DateTime"));
        }
        XElement time = doc.Element("DateTime");
        time.Add(new XElement("dateTime",
        new XElement("LastRunTime", DateTime.Now.ToString("g", DateTimeFormatInfo.InvariantInfo))));
        doc.Save(xmlFilePath);

Any suggestion/idea on the next step to get the time difference that stored in the XML file?

yancy
  • 17
  • 6
  • Please add code and data as text ([using code formatting](//stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](//meta.stackoverflow.com/a/285557). Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data. – gunr2171 Oct 27 '21 at 02:58
  • I don't understand what, precisely, you have a problem with. Reading the raw value from an xml node, parsing a string as a DateTime, or subtracting one DateTime from another? – gunr2171 Oct 27 '21 at 03:00
  • @gunr2171, problem of substract datetime with the previous one – yancy Oct 27 '21 at 03:14
  • Here's how to do that: [Difference between two DateTimes C#?](https://stackoverflow.com/questions/845379/difference-between-two-datetimes-c) – gunr2171 Oct 27 '21 at 03:15
  • It would be a good start to use ISO date/time formats rather than ambiguous US format, since that's what most libraries are likely to work with. – Michael Kay Oct 27 '21 at 07:20

1 Answers1

0

Use DateTime.Parse or DateTime.TryParse to convert string from xml back to DateTime, then DateTime.Subtract to get different hours. You should consider take a look at DateTime API here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-5.0