Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I need only to format time (00-23) & (HH: MM) in c#
and how do I insert this time in field Sqlserver 2012
and then fetch time and compare with another field?
thanks
Posted

Hi,

Use Upper case "HH" for 24hr format.
String s = date.ToString("HH:mm");

Reference here.

Once you get the correct format in C# you can pass that as string to sql server and save that string vaue in a varchar field.

Thanks
Sisir Patro
 
Share this answer
 
When you want the Time from a DateTime into an TimeSpan:
//The 01.01. in the first Year at 12:37
DateTime date = new DateTime(0001,01,01,12,37,00);

TimeSpan span = new TimeSpan(date.Ticks);

span will be 12 hours and 37 minutes

When you just want the DateTime or TimeSpan as readable String:
C#
String s = date.ToString();
String s = span.ToString();


Or maybe you read here^ on how to use format Strings:
Quote:
d: 6/15/2008
D: Sunday, June 15, 2008
f: Sunday, June 15, 2008 9:15 PM
F: Sunday, June 15, 2008 9:15:07 PM
g: 6/15/2008 9:15 PM
G: 6/15/2008 9:15:07 PM
 
Share this answer
 
v5
As mentioned in Solution 1 you can use the method DateTime.ToString in order to customize the date in the format you want.
See MSDN: Custom Date and Time Format Strings[^] for more information about the available formatting options.

The store as a string in a column in your database.

If you want to retrieve the string and convert back to DateTime again, you can use DateTime.ParseExact[^].

For example:
C#
string tmp = "22:32";
DateTime receivedDate = DateTime.ParseExact(tmp, "HH:mm", null);

In order to compare two date values, you just do a subtraction and put the result into a TimeSpan[^] type.
C#
TimeSpan difference = DateTime.Now - receivedDate;
 
Share this answer
 
C#
int hour = DateTime.Now.Hour;
               int minute = DateTime.Now.Minute;
               int second = DateTime.Now.Second;

               TimeSpan s = TimeSpan.Parse(hour.ToString() + ":" + minute.ToString());
               string strStartAndExitTime = s.ToString();

and
insert into database strStartAndExitTime
 
Share this answer
 
Since SQL Server 2008 there is a time sqldbtype which is compatible with .NET's timespan reference here[^]
or you can store the ticks from the timespan in a BigInt (if you need more than 24 hours).
Another technique I used to use "back in the day" was to multiply the hours by 10000, the minutes by 100 then add the seconds ... e.g. "11:03:15" becomes 110315 which can be stored in a BigInt.

All of these methods lend themselves to subsequent comparisons.

Edit - found the exact post I was looking for here[^]
 
Share this answer
 
v2

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