Link to home
Start Free TrialLog in
Avatar of jenvin
jenvin

asked on

Date Format Issues in ASP.Net

Hi .
I have a few issues regarding the Date Formatting in ASP.Net.
The User will enter the dates in 'dd-MM-yyyy' format

I have written the following procedure to return the formatted date according to the Parameter specified
====================

    Public Shared Function ReturnFormattedDate(ByVal Date_String As String, ByVal Date_Type As Integer) As String
            Dim GB As New CultureInfo("en-GB")
        Dim US As New CultureInfo("en-US", False)
        Dim ClcDate As Date
     
        If Date_Type = 0 Then
                     ClcDate = CDate(Date_String)
           ReturnFormattedDate = ClcDate.ToString("d", US.DateTimeFormat) ''MM-dd-yyyy

        ElseIf (Date_Type = 1) Then
            ClcDate = CDate(Date_String)
            ReturnFormattedDate = ClcDate.ToString("G", US) ''MM-dd-yyyy hh:mm:ss tt
        ElseIf Date_Type = 2 Then
            'ClcDate = CDate(Date_String)
            ReturnFormattedDate = ClcDate.ToString("d", GB) ''dd-MM-yyyy
        ElseIf Date_Type = 3 Then
            ClcDate = CDate(Date_String)
            ReturnFormattedDate = ClcDate.ToString("G", GB) ''dd-MM-yyyy hh:mm:ss tt
        ElseIf Date_Type = 4 Then
            ClcDate = CDate(Date_String)
            ReturnFormattedDate = ClcDate.ToString("T", GB) ''hh:mm:ss tt
        End If
     End Function

===============
But the  Above procedure does give error if the date is > 12
If User enters date as 28-07-2007, sometimes i want that date to be formatted to '07-28-2007' which is not happening here. Plz have a look and suggest me.
Thanx in Advance
Jenvin


Avatar of TSmooth
TSmooth

Try using the Date.TryParseExact() static method. This will allow you to make sure that the date is being input in the format you expect. I believe your code is by default assuming MM-dd-yyyy when you use CDate().

To first get your date_string into a proper date object try the following:
If Date.TryParseExact(Date_String, "dd-MM-yyyy", Nothing, System.Globalization.DateTimeStyles.None, ClcDate) = False Then
  Response.Write("Date was not of the correct format") ' Do your error handling here.
End If

This will properly convert the date_string to a date object based on the specified format. You can also use an array of acceptable formats as the second parameter to the TryParseExact method and you can also look into the other parameters on MSDN to see if you need to use any of them.
ASKER CERTIFIED SOLUTION
Avatar of william007
william007

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jenvin

ASKER

Thankx William007.
It is working that way.
Thanks to Tsmooth too

jenvin
Hi jenvin, if your problem has been solved, you should consider accepting the answer(s) that helped you:)