• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 44043
  • Last Modified:

VB.NET: Convert Date string and Time string to DateTime value

I have a web app developed in Visual Studio (vb.net) that ties to a SQL Server database.  One of the fields in the database is a datetime field.  The form has two text boxes, txtDate, and txtTime.  txtDate takes a regular expression along standard m/d/yyyy format (e.g., "1/1/2007", "12/13/2007").  txtTime takes a regular expression along standard time notation (e.g., "5:00 PM", "12:00 PM", "4:21 PM").

I need to convert these two separate strings into a datetime object so I can store it in the database.

I know this sounds simple, but I've been having a ton of problems with dates, times, datetime, and timespans.  It's not quite intuitive.

Any help?
0
kmoloney
Asked:
kmoloney
  • 4
  • 4
  • 2
  • +3
3 Solutions
 
Arthur_WoodCommented:
Dim NewDateTime as DateTime =cType(txtDate.Text & " " & txtTime.Text, DateTime)

txtMyDateTime = NewDateTime

The additional " " is important.

AW
0
 
drichardsCommented:
That is correct.  Same thing but a bit more .NET-ish and less VB-ish:

    Dim dt As DateTime = DateTime.Parse(txtDate.Text + " " + txtTime.Text)
0
 
Arthur_WoodCommented:
6 to one, half dozen to the other.

The two are functionally identical.

You pays your money, and you takes your choice.

Can you say split the points?? LOL   ;-}

AW
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just a minor note...

With VB.Net 2005, I would use one of the DateTime.TryParse() methods, instead of DateTime.Parse(), as it allows for easier code to be written:
http://msdn2.microsoft.com/en-us/library/ch92fbc1.aspx
0
 
drichardsCommented:
Yes, TryParse is useful if your input format is not validated and you expect failures.  Parse defers to TryParse internally anyway and throws an exception if TryParse returns false.

And no, I don't expect any point splitting - it was just a reaction to seeing a lot of questions about converting VB to C#.  It's an easier process if you stick to the framework ways of doing things rather than using VB-specific syntax.  As AW points out, the net result is the same.  In fact, the CType statement ultimately calls DateTie.TryParse as well.  Everything ends up in the same happy place.
0
 
kmoloneyAuthor Commented:
will this work with the regular expressions for a "DATE" and a "TIME":

DATE regex:

(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?\d\d

TIME regex:

([0-2])?\d:\d\d [AP]M

I guess I'll try it and find out.

BTW, its up to me if I want to split points... :-)
0
 
kmoloneyAuthor Commented:
Error received:

Conversion from string "" to type double is not valid.
0
 
kmoloneyAuthor Commented:
Here's my code (if they leave the time field blank, it's assumed to be 5:00 PM)

    Private Sub DetermineDateTimeFormat(ByRef strBody As String)
        '// DETERMINE THE DATE FORMAT TO BE PRESENT IN THE LETTER
        If Me.txtTermTime.Text = "" Then
            t.TerminationDateTime = CType(Me.txtTermDate.Text & " " & "5:00 PM", System.DateTime)
        Else
            t.TerminationDateTime = CType(Me.txtTermDate.Text & " " * Me.txtTermTime.Text, System.DateTime)

        End If
    End Sub
0
 
drichardsCommented:
You've got a '*' where a '&' shoudl be in the else clause:

t.TerminationDateTime = CType(Me.txtTermDate.Text & " " * <--- here
Me.txtTermTime.Text, System.DateTime)
0
 
drichardsCommented:
Not sure what you're doing with the regex, but they are somewhat oversimplified.  The time ones are not too bad to improve:

12 hour - probably need some variants on the am/pm:
^(?:[0]?[0-9]|1[0-2]):[0-5][0-9][ap]m$

24 hour with two digit hour:
^(?:[0-1][0-9]|[2][0-3]):[0-5][0-9]$

To get the dates correct with the number of days and such is much more complicated.  Your simple expressions will validate the formats but won't tell you if the values are legal.
0
 
kmoloneyAuthor Commented:
I liked Arthur Wood's solution the best, as IS more VB-ish.

Drichards offered a perfectly valid alternative, and pointed out the typo - something that I should have caught quickly - had I been looking in the write place to begin with.  Also, his suggestion re the regex'es, while not really a part of the question, will be useful.  I'll probably be using the "IsDate" function to test for it to be a valid date AFTER it matches the regex -- I'm not a regex master by any means, and I'm not planning on trying to come up with one that takes the different days of the month or leap years into accout.

Thanks, Guys.

Kevin

P.S. - it ends up like the points split after all! :-)
0
 
rheitzmanCommented:
I always use IsDate(txtString) in a QA step before using the values.

If Not IsDate("User entered stuff") then
  ... err message
0
 
dba123Commented:
>>>6 to one, half dozen to the other

not really, each has it's own purpose.  Doing a conversion is not something you just blankly state doesn't matter.  Each way of doing a conversion in .NET has its performance issues, complications, and considerations that you need to be aware of.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 4
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now