Click here to Skip to main content
15,923,015 members
Please Sign up or sign in to vote.
1.00/5 (2 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
Comments
BillWoodruff 2-Jan-15 3:48am    
So, you plan to discard year/month/day information ?
vajihe.mirzaei 2-Jan-15 4:12am    
yes I'm Iranian and we have a Jalali calendar
I must use this calendar and only need the time
but I have a problem ....
vajihe.mirzaei 2-Jan-15 4:33am    
can you help me?

you can insert Time column value as TimeSpan.
saple code:[^]
C#
using (SqlConnection cn = new SqlConnection(connstring))
using (SqlCommand cmd = new SqlCommand("Insert into Events (EventName, EventStartTime) values (@Name, @Start)", cn))
{
   cmd.Parameters.AddWithValue("@Name", "Thanksgiving Dinner (East Coast USA)");
   cmd.Parameters.AddWithValue("@Start", new DateTimeOffset(2007, 11, 22, 16, 0, 0, new TimeSpan(-5, 0, 0)));
   cn.Open();

   cmd.ExecuteNonQuery();

}
 
Share this answer
 
Do not change anything. Store date and time as a DateTime data type. There is no way to compare string: "22:22" to "20:15". Which one is bigger or less than other? String is a string, not date/time.

You'll be able to compare datetime data field this way:
SQL
SQL
DECLARE @t1 DATETIME = '2015-01-01 00:00:00'
DECLARE @t2 DATETIME = GETDATE()

SELECT DATEDIFF(HH,@t1,@t2) AS DiffInHrs


C#
DateTime.Compare method[^]
 
Share this answer
 
Hi,
All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
C#
TimeSpan span = TimeSpan.Parse("01:20");

If you want a DateTime, add that time to the min value:
C#
TimeSpan span = TimeSpan.Parse("01:20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 01:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting
 
Share this answer
 
Use below code and assign date to datetime variable.

DateTime dt = DateTime.Now;
string time = dt.ToString("HH:MM");
 
Share this answer
 
Comments
CHill60 5-Jan-15 7:49am    
And where is the bit that answers the question about the database storage? How will the OP be able to accurately compare that string with another time?
Mukesh.Ce62 5-Jan-15 7:59am    
You have to store datetime in database after then get date in backend and store in datetime object.

DateTime dtStart = DateTime.Now.Date; // here your date

then you can compare with other data like below
DateTime dtend = DateTime.Now.Date;
DateTime final = Convert.ToDateTime(dtend.Date - dtStart.Date);

And in last you can give format to your compared date.
string time = final.ToString("HH:MM");

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