0

I am trying to convert a string into DateTimeOffset. here is an example of my string 2017/010/23:51:50 2017 represents year 010 represent day of the year and 23:51:50 is time. I am trying in below way but it returns me 0001-01-01 00:00:00.0000000 +00:00 always no mater the input is. My code

DateTimeOffset DateTime;
string year = ("2017/010/23:51:50");
DateTimeOffset.TryParse(year, out DateTime);

Any suggestion please?

Update For simplicity I did not linger my question. My date time I am getting year (2017 it could be 2002, 2001 ) from name of a .txt file and day and time (010/23:51:50 some has offset and some content don't) from the content of that .txt file. So my input is not always same. hope this clarifies

10
  • When you say day of the year, do you mean like from 1 to 365? Commented Oct 12, 2017 at 16:25
  • 2
    It returned false, never ignore that. Use Parse() instead to keep yourself honest. Commented Oct 12, 2017 at 16:25
  • You are correct @OfirWinegarten Commented Oct 12, 2017 at 16:28
  • Why are you using DateTimeOffset? The date string doesn't contain offset information. Is it in UTC? Commented Oct 12, 2017 at 16:28
  • 1
    Possible duplicate of Parsing a DateTimeOffset string in C# Commented Oct 12, 2017 at 16:34

2 Answers 2

2

First split the string by / and then use the dayOfTheYear value and the year to obtain the year/month/date. Next split the time parameter and use it to obtain TimeSpan and add it to the previously obtained date. Next, simply parse your newly obtained date to DateTimeOffset. This code should work:

        string year = ("2017/010/23:51:50");
        var date = year.Split('/');
        var timeSpanVal = date[2].ToString().Split(':').Select(x=>Convert.ToInt32(x)).ToList();
        TimeSpan ts = new TimeSpan(timeSpanVal[0], timeSpanVal[1], timeSpanVal[2]);
        DateTime newDate = new DateTime(Convert.ToInt32(date[0]), 1, 1).AddDays(Convert.ToInt32(date[1]) - 1)+ts;

        DateTimeOffset.TryParse(newDate.ToString(), out DateTime);
Sign up to request clarification or add additional context in comments.

1 Comment

One doesn't need to go through a string to convert from DateTime to DateTimeOffset. However, you do need to know what offset you want to use.
1

Looking through the date and time formats, I don't think you can parse the format Year/JulianDay/Time. What you can do is split the string into parts and then add the days to the year

string[] parts = year.Split('/');
DateTime dt = new DateTime(int.Parse(parts[0]), 1, 1); 
dt = dt.AddDays(int.Parse(parts[1]) - 1).Add(TimeSpan.Parse(parts[2]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.