Home > Blockchain >  Convert Time and Date in string to date VB.net
Convert Time and Date in string to date VB.net

Time:12-10

I'm using RSS feeds from multiple sources and I'm sorting the feeds by date. However, the dates I receive are in different time zones.

This is the format of some of the date strings that I get:

Wed 08 Dec 2021 01:40:31 -0500 Wed 08 Dec 2021 11:11:19 -0600

The "-500' indicates the time zone which is UTC-5. I need to use that "-0500" to convert this string into a date and the date needs to be only in UTC.

Basically from "Wed 08 Dec 2021 01:40:31 -0500" to "12/08/2021 06:40:31"

I've managed to split the string up to sort by date but because of the time difference, it doesn't really help.

Is there coding which I can use to convert the string as-is into date and only UTC time? Or is there just a place where I can start?

Thank you in advance.

CodePudding user response:

Using DateTime.ParseExact, you specify a format to convert from, and that can include "zzz" for the timezone offset. You can also specify that you want the result in UTC:

Dim s = "Wed 08 Dec 2021 01:40:31 -0500"
Dim d = DateTime.ParseExact(s, "ddd dd MMM yyyy HH:mm:ss zzz", Nothing, Globalization.DateTimeStyles.AdjustToUniversal)

Console.WriteLine(d.ToString("yyyy-MM-dd HH:mm:ss"))
Console.WriteLine(d.Kind.ToString())

Outputs:

2021-12-08 06:40:31
Utc

Of course, format the result as you desire.

Alternatively, if you need to, you can keep the offset by using a DateTimeOffset structure and adjust it to UTC for representation as a string:

Dim s = "Wed 08 Dec 2021 01:40:31 -0500"
Dim d = DateTimeOffset.ParseExact(s, "ddd dd MMM yyyy HH:mm:ss zzz", Nothing)

Console.WriteLine(d.ToUniversalTime.ToString("yyyy-MM-dd HH:mm:ss"))

Outputs:

2021-12-08 06:40:31

  • Related