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

Converting a string to DateTime for formatting?

I have the following string: 2008-10-17

How would I go about formatting this into : 17/10/2008

I was thinking the easiest solution would be to create a DateTime object and set the date to : 2008-10-17. Then format the date element.

But I am not certain how I would set the date element of the DateTime. Obviously I would be open to far better options?
0
directxBOB
Asked:
directxBOB
  • 2
1 Solution
 
ladarlingCommented:
The datetime object has built in return overloads. Try this:

Dim someDate As String = "2008-10-17"
Dim realDate As DateTime
realDate = Date.Parse(someDate)
MsgBox(realDate.ToShortDateString)
 
0
 
directxBOBAuthor Commented:
Cheers that works but not in the case where dates would be in the format of:

17/10/2008
or
17/10/08

Any ideas on how to get that formatted correctly?
0
 
ladarlingCommented:
Those two formats would be really problematic unless they were standard throughout the application and there was not the possibility of getting well-formed dates confused with them. What I mean is:
4/5/2008, in this scenario, could mean April 5th, 2008, or it could mean May 4th, 2008. Not good.
But, if you know that you are always going to recieve dates is that format, you can fix them with something similar to:
 

 Public Function FixDate(ByVal aDate As String) As DateTime
        Dim theDay, theMonth, theYear As String
        theDay = Mid(aDate, 1, 2)
        theMonth = Mid(aDate, 4, 2)
        theYear = Mid(aDate, 7) 'Take the rest of the digits
        Return DateTime.Parse(theMonth & "/" & theDay & "/" & theYear)
 
 End Function

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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