Breaking News

Tuesday, October 5, 2010

How to: Convert string to Time

Generated from this question, I thought it might be helpful for others looking for something similar.

Incoming data: 1000 (string format)
Desired output: 10:00 AM

C# Code:
string str = "1000";//drv.Row("arrival_time")
string[] formats = new string[] { "HHmm" };
DateTime dt = DateTime.ParseExact(str, formats,
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    System.Globalization.DateTimeStyles.AdjustToUniversal);
string strTime = dt.ToShortTimeString();

DateTime dte = DateTime.Now;
IFormatProvider culture = new System.Globalization.CultureInfo("en-GB", true);


VB.NET Code:
Dim str As String = "1000" 'drv.Row("arrival_time")
Dim formats As String() = New String() {"HHmm"}
Dim dt As DateTime = DateTime.ParseExact(str, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal)
Dim strTime As String = dt.ToShortTimeString()

Dim dte As DateTime = DateTime.Now
Dim culture As IFormatProvider = New System.Globalization.CultureInfo("en-GB", True)

Outputs:
10:00 AM

Note, if you plan on using that frequently, you might want to add that as an extension method.

C# Code:
public static class Extensions
{
    public static string ToTime(this string str)
    {
        DateTime dt = DateTime.Now;
        try
        {
            string[] formats = new string[] { "HHmm" };
            dt = DateTime.ParseExact(str, formats,
                                                System.Globalization.CultureInfo.InvariantCulture,
                                                System.Globalization.DateTimeStyles.AdjustToUniversal);
        }
        catch
        { throw new Exception("Invalid data"); }
        return dt.ToShortTimeString();
    }
}


VB.NET Code:
Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
     _
    Public Shared Function ToTime(str As String) As String
        Dim dt As DateTime = DateTime.Now
        Try
            Dim formats As String() = New String() {"HHmm"}
            dt = DateTime.ParseExact(str, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal)
        Catch
            Throw New Exception("Invalid data")
        End Try
        Return dt.ToShortTimeString()
    End Function
End Class



How to call the extension method:
string str = "13000";//SomeDataRowView.Row("TIME_COLUMN")
string strTime = str.ToTime();


VB.NET Code:
Dim str As String = "13000" 'or SomeDataRowView.Row("TIME_COLUMN")
Dim strTime As String = str.ToTime()

Run in debug (VB.NET):


Happy "Dating"! (0;

No comments:

Post a Comment

Designed By Published.. Blogger Templates