views:

75

answers:

2

I am working with DateTime, trying to get date in the format like this:

03.05.2010-04.05.23 that is: dd.MM.yyyy-HH.mm.ss

I'm using DateTime.ParseExact to try to achieve this (maybe wrong)

So far I have:

var dateInFormat = DateTime.ParseExact(DateTime.Now.ToShortDateString(), "dd.MM.yyyy.HH.mm.ss", null);

But can't quite get exactly what I want. Basically I want to keep the 0, for example time is 05:03:20 PM I don't want it to show like 5:3:20 PM

Any ideas?

+1  A: 

Is there any problem just using ToString()? Eg:

Console.WriteLine(dateInFormat.ToString("dd.MM.yyyy-HH.mm.ss"));
leppie
sorry, I should've explained, actually it crashes on that line: `FormatException`: String not recognized as a valid DateTime
baron
Should'nt if be `DateTime.Now.ToString(...)`?
Jens
@Jens: any DateTime will do, wont it?
leppie
@baron: Your parsing string is different from what you have. Notice the missing `-`.
leppie
+1  A: 

If you have a date as DateTime (not string) then you can format it as leppie indicates:

  string date = DateTime.Now.ToString("dd.MM.yyyy-HH.mm.ss");

If on the other hand you have a date as string in the format dd.MM.yyyy-HH.mm.ss then you can use

 string mydate = "03.05.2010-04.05.23";
 DateTime dateFromString = DateTime.ParseExact(mydate, "dd.MM.yyyy-HH.mm.ss", null);

you get the exception because your string has the wrong format (namely the systems short date format)-

Stefan Egli
Actually I am just trying to Parse the time "right now" into that format, which is why I used `DateTime.Now.ToShortDateString()`
baron
see my revised answer
Stefan Egli
@baron: you seem to be confusing the terms. Parsing usually means taking a string and obtaining structured data from it (like a DateTime). If you start with a DateTime (what you get from DateTime.Now), you're not parsing.
Martinho Fernandes
but i'm still trying to turn that data into a different format - not sure whether my format keeps it still as DateTime I think it probably does ?
baron