Link to home
Start Free TrialLog in
Avatar of zipnotic
zipnoticFlag for United States of America

asked on

Simple Time Conversion question

Hello,

Trying to convert a time given to me in this format:

MyDate = 9/20/2016 4:30:32 PM -07:00

4:30 PM is 'universal time' and -7 is the offset for the time zone in question.  I want to get the local time according to the offset, not the time zone on the users computer.  So for the above example it should kick back "9/20/2016 9:30 AM"  in the variable LocalDate.  Having a lot of trouble with something so simple...

Dim LocalDate as datetime
Dim diditwork As Boolean = DateTime.TryParse(MyDate, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, LocalDate)

dim NewDate as DateTime
LocalDate = DateTime.SpecifyKind(LocalDate, DateTimeKind.Utc)
NewDate = LocalDate.ToLocalTime




Thanks for ideas

zip
Avatar of it_saige
it_saige
Flag of United States of America image

See if this does what you request (source: https://msdn.microsoft.com/en-us/library/bb546101(v=vs.110).aspx):
Imports System.Globalization
Module Module1
	Sub Main()
		Dim utc As DateTime
		Dim offset As DateTimeOffset
		Dim local As DateTime
		DateTime.TryParse("9/20/2016 4:30:32 PM -07:00", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, utc)
		offset = New DateTimeOffset(utc, TimeZoneInfo.Utc.GetUtcOffset(utc))
		local = offset.DateTime.ToLocalTime

		Console.WriteLine("{0} converts to {1} {2}", offset, local, local.Kind)
		Console.ReadLine()
	End Sub
End Module

Open in new window


-saige-
Avatar of zipnotic

ASKER

Hmm,

Doesn't seem to be working as desired.  

                                Dim utc As DateTime
                                Dim offset As DateTimeOffset
                                Dim local As DateTime
                                DateTime.TryParse("9/20/2016 4:30:32 PM -07:00", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, utc)
                                offset = New DateTimeOffset(utc, TimeZoneInfo.Utc.GetUtcOffset(utc))
                                local = offset.DateTime.ToLocalTime
local still  = "9/20/2016 4:30:32 PM"
where it should be "9/20/2016 9:30:32 AM"


watching while debugging it looks like utc is going the wrong way (as in ADDING 7 hours instead of subtracting).  The time given to me is UTC and the offset is where I want to go to.

Thanks for you input!
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

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
Sure enough, elegant, simple solution in one line of code.  Why do simple problems seem the most perplexing sometimes?

Sheesh, thanks a bunch.  

Z
Great response and follow up.  An elegant solution I wouldn't have thought up in 2 years.