tags:

views:

56

answers:

3

Hey there, I am extracting the date and time of creation of a file. the date should be 7/1/2010 2:08 PM but the format comes out as 2:08:07 01/07/2010 when called from my application. I would like it show as it does in the file explorer (7/1/2010 2:08 PM). How can I accomplish this?

    string createdOnCMM = Creationtime; //this returns the 2:08:07 01/07/2010 


// I think I need a modified verison of the following to reformat it

    DateTime dt = Convert.ToDateTime(createdOnCMM);
    String.Format("0:{dd/MM/yyyy HH:mm:ss}", dt);
+3  A: 

Your compound format string isn't quite right. Try this:

string s = string.Format("{0:dd/MM/yyyy HH:mm:ss}", dt);

Alternatively, if you only want to format the DateTime, call ToString directly:

string s = dt.ToString("dd/MM/yyyy HH:mm:ss");

(That's a more readable approach, IMO.)

Note that this is very culture-specific at the moment. That may be okay for your intended use, but you should be aware of it.

Jon Skeet
+1  A: 

If you just need to format with your current culture's short date string then use the g specifier as mentioned in Eric's answer.

If you need the exact format that you mentioned, regardless of your current culture, then one of the following should do the trick:

string formatted = dt.ToString("M'/'d'/'yyyy h':'mm tt");

// or

string formatted = string.Format("{0:M'/'d'/'yyyy h':'mm tt}", dt);
LukeH
+1 for the '' around / and : for being locale independent!
jdehaan
this displays 1/7/2010 2:08:07PM ... i would really like it to be 7/1/2010 2:08:07PM
jakesankey
THANKS ... displays properly now.. it thinks that the 07 is the day when in reality that is actually July. but it displays correctly nontheless.
jakesankey
@jake: I just edited my format string back to its original, correct form (which, unfortunately, is giving you the undesired results). The problem is that the `DateTime` itself is incorrect. Your `Convert.ToDateTime` call is interpreting the day part of `createdOnCMM` as the month and vice-versa.
LukeH
+3  A: 

From Microsoft's Standard Date and Time Format Strings, you should be able to get what you want by using the g format string like the following:

String.Format("{0:g}", dateTimeValue);

That should yield the format you'd like.

Eric
As Jon mentioned, your format string needs to be fixed as well.
Eric
this displays 1/7/2010 2:08:07PM ... i would really like it to be 7/1/2010 2:08:07PM
jakesankey
Yup, sorry--I didn't notice that. Then using Jon's format string will yield what you want. Notice that the '0:' is inside the curly braces.
Eric