-1

Below is the string I got from a REST API to Sonatype Nexus. As I want to delete anything older than 60 days. How to write this code in C#?

<lastModified>2016-08-11 14:12:26.37 UTC</lastModified>
Jirong Hu
  • 2,315
  • 8
  • 40
  • 63
  • 5
    What have you tried? How is the behavior of what you've tried different from the expected result? Please post a [MCVE](http://stackoverflow.com/help/mcve). – Lews Therin Aug 11 '16 at 17:46
  • 3
    you need to use datetime.tryparse – pm100 Aug 11 '16 at 17:47
  • I found another post, works well: http://stackoverflow.com/questions/528368/datetime-compare-how-to-check-if-a-date-is-less-than-30-days-old – Jirong Hu Aug 11 '16 at 18:28

1 Answers1

0

Assuming your API will always return <lastModified> and </lastModified> .. The following will do what you want.

var MyString = "<lastModified>2016-08-11 14:12:26.37 UTC</lastModified>";
MyString = MyString.Substring(14);
MyString = MyString.Replace("UTC", "");
MyString = MyString.Substring(0, MyString.Length - 15);

DateTime MyDateTime = new DateTime();
DateTime.TryParse(MyString, out MyDateTime);

if (MyDateTime < DateTime.Now.AddDays(-60) && MyDateTime != new DateTime(0001, 1, 1))
{
    //Do  Your Code
}
mituw16
  • 5,126
  • 3
  • 23
  • 48
  • Instead of using `Substring`, I would use `Replace` to remove the tags : `MyString.Replace("", string.Empty);` Magic numbers are my nemeses. – Beltaine Aug 11 '16 at 18:11
  • The substring resolved my another issue. I was using "yyyy-MM-dd HH:mm:ss.fff UTC" to parse, but found sometime the return string sometime ends with ff, or f. – Jirong Hu Aug 11 '16 at 18:27