Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I get only time in c# and how to do I store time in database.

Example: 09:00 am.
Posted
Updated 1-Feb-14 19:27pm
v2

Try this:
DateTime.Now.ToShortTimeString().ToString()



This will retrieve just time part from your DateTime.
 
Share this answer
 
Comments
Karthik_Mahalingam 1-Feb-14 0:04am    
5,
.ToString() is no needed. since .ToShortTimeString() will returns a string value..
Jignesh Khant 1-Feb-14 0:08am    
Karthik I have used above code in multiple projects & it works fine.
Karthik_Mahalingam 1-Feb-14 0:18am    
Jignesh, i didnt say it will not work..
i know you code is fine..
my suggestion is .ToString() is of no use..
remove that and see. you will get the same output :)
Member 10548723 1-Feb-14 1:03am    
time(7), what does (7) means. if i want to store something like 09:00 am . I use time(7)
if you need to store only time then you can store in Time data type, if your sql server version is older and not supporting time date type, then you can store in datetime and get only time in select query or also can store in varchar or nvarchar type.

and for getting time from c# code you can use like this...

C#
string time = DateTime.Now.ToString("hh:mm:ss t");
string time = DateTime.Now.ToString("HH:mm:ss"); //for geting time in 24 hrs format
 
Share this answer
 
Comments
Member 10548723 1-Feb-14 0:07am    
Time(7) or timestamp data type is possible?
try with this code. Store time in database as nvarchar

C#
TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = date.ToString("hh:mm tt");
 
Share this answer
 
Comments
Member 10548723 1-Feb-14 0:07am    
Time(7) or timestamp data type is possible?
V5709 1-Feb-14 0:20am    
yes.. you can convert it in time(7) by using sql query.Run following sql query.Hope it will solve your problem..

----------------

declare @time nvarchar(50)=null;
set @time='09:00 am';
SELECT CONVERT(time(7),@time);

---------------------
In C# you can do like :

C#
TimeSpan dt = DateTime.Now.TimeOfDay;
           Console.WriteLine(dt);



And in SQl Server you can do like:

SQL
declare  @timetable table
(
	UserTime Time
)

insert  into @timetable values('02:24:56.180')

SELECT * FROM @timetable
 
Share this answer
 
Comments
Member 10548723 1-Feb-14 0:08am    
How you convert from timespan variable to string
if you want to store time as timespan. Try This
DateTime dt = DateTime.Parse(Datetime.Now.ToString("hh:mm tt"));
TimeSpan ts = new TimeSpan(dt.Hour, dt.Minute, dt.Second);
 
Share this answer
 

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