tags:

views:

824

answers:

8

hi guys, I have a dropdownlist that displays time only.Like 8:00AM,8:30AM............When i save this time to database i want to save as todays date + time. eg:8:00AM as 03/30/2009 8:00:00:000.Can anybody give appropriate code to convert as above shown eg:

I tried Convert.ToDateTime(ddlStartTime.SelectedItem.Text) the one error is showing as "String was not recognized as a valid DateTime."

A: 

Read the parts of the time so you have hours and minutes, then use the following code:

DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
ck
Does this work in vb??
AnthonyWJones
Also how is AM/PM handled?
AnthonyWJones
This solution may be slightly flawed but it is still cleaner than some of the other solutions presented here.
Cerebrus
@AnthonyWJones: remove the semicolons, and handle the AM/PM in the hours retrieval. @Portman, it uses DateTime.Now.Date, which returns the date part only, not the time.
ck
+2  A: 

Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.

Untested Code.

DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
    DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Craig
how is that code.can u show 1 eg:
Nice! You can drop the AddHours() and AddMinutes(). DateTime.Parse, when parsing a time only, will automatically set the date to today.
Portman
Thanks Portman, I didn't have VS in front of me to try.
Craig
+2  A: 

Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-

valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))

By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.

AnthonyWJones
This solution is needlessly complicated. I do not see any need to calculate the no. of minutes from midnight.
Cerebrus
The time value and the visual representation of the time are "needless" coupled. It's better to have them decoupled. If the customer wants to change the presentation of time to say, 24 hour, then only the code generating the presentation need change.
AnthonyWJones
+1  A: 
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);

Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.

Portman
Sorry, I do not know how to translate this to VB.NET. Anyone is welcome to poach this logic and write a VB.NET answer.
Portman
Way too much use of var, you've made this .net 3+
ck
+2  A: 

Basically, you just need to parse the time string. It will be automatically resolved to the current date.

Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
  'Parse was successful.
Else
  'Handle the error.
End If
Cerebrus
Binding the value of field to its current textual representation is not really a good idea. If the textual representation is changed then the code to parse it needs to change. Thats why HTML option has a value attribute so that value and presentation can be decoupled.
AnthonyWJones
And yet, that is a decision made by the OP. I presented a solution on the basis of the OP's existing setup. It is apparent from the question that the SelectedItem.Text property is being used, not the Value property.
Cerebrus
Quite so, my suggestion then is to stop using Text and leave that for presentation and start using Value which is set to a simple unambiguous value.
AnthonyWJones
A: 

Use ParseExact so that you can specify the format that you are using.

h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator

Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)

The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.

Guffa
+3  A: 

VB.NET answer for Portmans Solution. Too many chars for comment so included here.

Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
  ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Wayne
@ramyatk06: you should un-accept my answer and accept this one, since your question specifically asks about VB.NET.
Portman
A: 

This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.

DateTime dTime = DateTime.Now;

string time = this.DropDownList1.SelectedValue;

DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() + " " + time);