-1

I was wondering if it is possible to convert custom formatted DateTimes to something more standardized.

I have two types of date-formats in string.

string Date1 = @"06.12.2015 18.00";
string Date2 = @"1944-09-29";

and I want to convert both to these kind of format:

yyyy-MM-ddThh:mm:ssZ

How do i do this?

I tried

DateTime testdate = DateTime.ParseExact(Date1, 
                                       "yyyy-MM-ddThh:mm:ssZ", 
                                        CultureInfo.InvariantCulture);

but with no luck.

EDIT: Thsi question was flagged as possible duplicate to another entry in StackOverflow. The difference here is, as Vadim Yarovikov in the comments below put it, a two part question. "1) Parse value to date and 2) Convert date to desired format."

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
H4p7ic
  • 1,669
  • 2
  • 32
  • 61
  • 2
    Possible duplicate of [C# DateTime to "YYYYMMDDHHMMSS" format](https://stackoverflow.com/questions/3025361/c-sharp-datetime-to-yyyymmddhhmmss-format) – Vadim Iarovikov Feb 07 '18 at 12:58
  • I wouldnt say this is the same question actually, in that example the problem is about formatting a Datetime.now. thsi is about converting and formatting a string to another type of date time format? Am i wrong here?@VadimYarovikov – H4p7ic Feb 07 '18 at 13:06
  • so your question consists of two different parts: 1) Parse value to date and 2) Convert date to desired format. – Vadim Iarovikov Feb 07 '18 at 13:15
  • Yes, sorry if i was a bit missleading. Thank you for the clarification though. – H4p7ic Feb 07 '18 at 13:22

1 Answers1

3

You can provide two formats in one DateTime.ParseExact call:

string[] tests = new string[] {
  @"06.12.2015 18.00", 
  @"1944-09-29" 
};

var result = tests
  .Select(item => DateTime.ParseExact(
     item,
     new string[] { "d.M.yyyy H.m", "yyyy-M-d" },
     CultureInfo.InvariantCulture, 
     DateTimeStyles.AssumeLocal))
  .Select(date => date.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture));

Console.WriteLine(string.Join(Environment.NewLine, result));

Outcome:

2015-12-06T18:00:00Z
1944-09-29T12:00:00Z

Side Note: I think that the actual target format should be "yyyy-MM-ddTHH:mm:ssZ" (please, notice HH instead of hh) otherwise it's impossible to distinguish 6:00AM and 6:00PM (18:00)

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Ahh i think i will try this but i want the conversion result to be in format: yyyy-MM-ddThh:mm:ssZ. Still Thank you alot ! :D @DemitryBychenko – H4p7ic Feb 07 '18 at 13:09