David Smith

David Smith

  • NA
  • 2k
  • 0

How to convert time to datetime

Dec 10 2012 7:36 AM
How to convert time to datetime.

I am trying to send time to a datetime column.

So if I have 12:00 PM,  how to convert to datetime , so i can send the value to the actual field in the database. I am trying to
insert the time values into the TimeFrom and TimeTo columns

Database columns,

ID, DateFrom, DateTo, TimeFrom, TimeTo

Answers (8)

8
Anuja Pawar

Anuja Pawar

  • 0
  • 1.5k
  • 178k
Dec 10 2012 8:02 AM
No, its not possible directly as time is duration and its not date. But if you have reference date then you can do it.
DateTime dt = new DateTime(2012, 01, 01);
 TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
 dt = dt + ts;
2
David Smith

David Smith

  • 0
  • 2k
  • 0
Dec 10 2012 9:24 AM
Understood, so would some good logic to  represent if a user choose anytime within a 24 hour time frame.
1
Sandeep Singh Shekhawat

Sandeep Singh Shekhawat

  • 0
  • 19.9k
  • 30.7m
Dec 10 2012 8:52 AM

TimeSpan ts = new TimeSpan(24);

DateTime dt = Convert.ToDateTime(ts.ToString());

 

Response.Write(dt);

 Output:
12/10/2012 12:00:00 AM 

1
Sandeep Singh Shekhawat

Sandeep Singh Shekhawat

  • 0
  • 19.9k
  • 30.7m
Dec 10 2012 8:40 AM

TimeSpan ts = new TimeSpan(12);

DateTime dt = Convert.ToDateTime(ts.ToString());

 

Response.Write(dt);

 
It will give following output :

12/10/2012 12:00:00 PM 


 
we can use dt variable for other operation ahead.



0
Mageshwaran R

Mageshwaran R

  • 0
  • 10.8k
  • 1.1m
Nov 23 2019 11:36 AM
Hi,
Try this code:
  1. var dateStr = "14:00";  
  2. var dateTime = DateTime.ParseExact(dateStr, "H:mm"null, System.Globalization.DateTimeStyles.None);   
0
Shebin babu

Shebin babu

  • 0
  • 6
  • 1
Nov 28 2018 12:30 AM
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
0
Vulpes

Vulpes

  • 0
  • 96k
  • 2.5m
Dec 10 2012 2:45 PM
If I were you, I'd use a fixed reference date.

The one that Anuja suggested - 1 January 2012 - is as good as any.

I'd then write a simple method which converts your time string into a DateTime representing the same time on the reference date:

  static DateTime GetDateTime(string timeStr)
  { 
     return DateTime.Parse("01/01/2012 " + timeStr);
  }

and call it with code such as this:

  DateTime dt = GetDateTime("12:00 AM");
  Console.WriteLine(dt); // 01/01/2012 00:00:00


0
David Smith

David Smith

  • 0
  • 2k
  • 0
Dec 10 2012 8:48 AM
Sandeep what if the value is 12 AM instead of 12PM, how would i get 12 AM

from your logic below.

TimeSpan ts = new TimeSpan(12);

DateTime dt = Convert.ToDateTime(ts.ToString());