Click here to Skip to main content
15,906,816 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi all :)

I want to get the date and time format like this: 2011-09-28 05:44:23 AM

I useDate
C#
Time _DateTime = DateTime.Now;
string _justdate = _DateTime.Date.ToString();


but it gives me alawys that date with time = 12:00:00 AM

how can I get the date and the time to insert it to datetime field at my database table

any help please ? :)
Posted
Updated 28-Sep-11 13:55pm
v2

Because you convert the _DateTime and use the ToString of the Date part of the variable. You can directly use DateTime.Now.ToString() to get datetime of the machine.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 28-Sep-11 20:16pm    
Correct, but format is not explained. Just ToString() (without parameters) will not give desired format. I answered...
--SA
Pradeep Shukla 28-Sep-11 20:20pm    
yes..you are right..I didn't notice the format in the question. It takes the default format based on the regional settings...
Don't work with date and time separately. From a certain point of view, there is no such thing as "date"; this is really just a sub-set of time points (range, programmers say, not quite correctly). In your case, the property Date is useless.

What you really need is time formatted using appropriate format specifier. See all the methods System.DateTime.ToString and format specifiers:
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^],
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^].

Note that IFormatProvider is supported by System.Globalization.CultureInfo for the parameter of System.DateTime.ToString(IFormatProvider), see http://msdn.microsoft.com/en-us/library/ht77y576.aspx[^].

In your case, you can use

C#
System.DateTime myTime = System.DateTime.Now;
string myTimeString = myTime.ToString("yyyy-MM-dd HH:mm:ss tt");


You did not explain what culture you need to apply for AM/PM, neutral or localized.

See the above references on how to have AM/PM localized, see the code sample: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#ttSpecifier[^].

—SA
 
Share this answer
 
v2
Comments
Pradeep Shukla 28-Sep-11 20:20pm    
you got it right..my 5+
Sergey Alexandrovich Kryukov 28-Sep-11 22:41pm    
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900