views:

38

answers:

5

I'm trying to make my string a nice formatted time but the column in the database isn't set up as a date/time field is there anyway I can do this?

Here's my query

Dim query as String = "Select * from openquery (devbook, 'SELECT wb.arrival_time FROM web_bookings wb ')"

And here's where i'm converting it

Session("formattime") = DateTime.Parse(drv.Row("arrival_time")).ToString("hh:mm")

The arrival_time field only has 4 numbers in like this 1000 so I need a way of converting it to a nice format like this 10:00AM

I'm using VB by the way

Any ideas?

Thanks

Jamie

A: 

The date may contain more than just hours and minutes. You need to check what is in arrival time

Shiraz Bhaiji
I have added a bit above which says what's in my arrival_time field and what outcome I'm looking for
Jamie Taylor
is the number an int or a string?
Shiraz Bhaiji
the number is a string
Jamie Taylor
Then you cannont us DateTime, read it as a string. Then use substring to divide it up.
Shiraz Bhaiji
A: 

I'm not familiar with the VB.NET syntax, but I'm thinking you could just use string.Split() on the arrival time value, to split it into hours and minutes, then convert that into a DateTime.
DateTime.Parse won't automatically realise that those 4 numbers are supposed to be hours and minutes.

Nellius
A: 

I assume that your input time is 3 or 4 digits representation of the time in 24 hour format that may have leading white space. You can then parse it like this:

Dim i As Int32
If Int32.TryParse(drv.Row("arrival_time")), NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, i) Then
  Dim hours As Int32 = i\100
  Dim minutes As Int32 = i Mod 100
  Dim ts As new TimeSpan(hours, minutes, 0)
  Dim dt As DateTime = DateTime.Now.Date + ts
  Session("formattime") = dt.ToString("hh:mm tt", CultureInfo.InvariantCulture)
Else
  ' Handle invalid time
End If

DateTime.Parse and friends is not able to parse time strings with only one digit for the hour hence this approach. Getting AM/PM right is not easy so that is delegated to the DateTime class.

Martin Liversage
This one doesn't error but it doesn't seem to work either it just gives me the else part output?
Jamie Taylor
A: 

Have a look at this http://blog.stevex.net/parsing-dates-and-times-in-net/

and

http://msdn.microsoft.com/en-US/library/8kb3ddd4.aspx

If you need the colon in there, and can guarantee that your DB field will always return a string with 4 characters you can do something like this to get the time in the right format.

string e = "1000"; // from db.
string t = string.Format("{0}:{1}", e.Substring(0, 2), e.Substring(2, 2));
Dave
This works as you say if it is 4 numbers unfortunately there is some with three number they are missing the preceding 0 is there anyway I can add this on if there is 3 numbers?
Jamie Taylor
+2  A: 

How about:

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

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

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

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--

Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    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

Example:

string str = "13000";//drv.Row("arrival_time")
string strTime = str.ToTime();

VB.NET

Dim str As String = "13000"
'drv.Row("arrival_time")
Dim strTime As String = str.ToTime()

Anything bad in the data will throw you an exception.

--EDIT--

Works fine in VB.NET.

alt text

KMan
Seem to be getting Argument not specified for parameter 'Number' of 'Public Function Str(Number As Object) As String' error with this one
Jamie Taylor
@Jamie Taylor: Please see my edit in response to your comment.
KMan
@KMan I converted it into VB.net the top one gives me an error String was not recognized as a valid DateTime and the bottom one gives me error Argument not specified for parameter 'Number' of 'Public Function Str(Number As Object) As String'
Jamie Taylor
@KMan the last one you added gives me an error 'ToTime' is not a member of 'String'
Jamie Taylor
@Jamie Taylor: Please see my edit in response to your comment. Its works fine in VB.NET
KMan
@KMan I can get it to work by using "1000" but when changing that for my database field it errors? Any suggestions? Thanks for you help and patience
Jamie Taylor
@Jamie Taylor: Can you post the error description?
KMan
@KMan Here's is the error String was not recognized as a valid DateTime. on Line 141: Dim dt As DateTime = DateTime.ParseExact(str, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal) seems to be where the error is
Jamie Taylor
@Jamie Taylor: Can you verify the incoming data? This sounds like the incoming data is not `1000` or similar. Try debug mode and add a watch to see if its really for the format `1000`.
KMan
@KMan just had a look at my data it appears that some fields only have 3 characters "940" instead of "0940" is there anyway I can add the preceding "0" if it needs it?
Jamie Taylor
@Jamie Taylor: Yes, use `str = str.PadLeft(4, "0"c)`. This would pad left with zeros. Meaning `940` would be `0940`, and `40`=`0040` and `4`=`0004`.
KMan
@KMan thanks that works great - by the way how do you code in the comments? I see you have done this in your previous post
Jamie Taylor
@Jamie Taylor: Same as you'd do in the editor, just that toolbar or shortcuts aren't available (0: For instance put your codes within the `(the grave accent key). Or for italics surround the text with * (star/asterisk).
KMan
@KMan Thanks again for your help and patience with me
Jamie Taylor