Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

vb.net - 如何将日期,时间和UTC偏移量转换为本地DateTime(How to Convert Date, Time and UTC Offset to Local DateTime)

I need to get a local timezone datetime from the following XML elements:

(我需要从以下XML元素获取本地时区datetime:)

<TransactionDate>20191202</TransactionDate>
<TransactionTime>234026</TransactionTime>
<TransactionTimezone>UTC-06:00:00</TransactionTimezone>

My local UTC offset is -05:00:00.

(我的本地UTC偏移量是-05:00:00。)

After getting TransactionDate and TransactionTime into td and tt Date variables, I can build a Datetime like this:

(将TransactionDate和TransactionTime放入td和tt Date变量后,我可以像这样构建Datetime:)

Dim ldDate As New Date(td.Year, td.Month, td.Day, tt.Hour, tt.Minute, tt.Second)

I could parse out the '-06' from TransactionTimeZone and determine that I need to add 1 hour to ldDate, but there must be a more elegant way.

(我可以从TransactionTimeZone中解析出“ -06”,并确定我需要向ldDate添加1小时,但是必须有一种更优雅的方法。)

Any ideas?

(有任何想法吗?)

  ask by Peter Kipe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have transactions from all the world this might help you to use as a base and working on to improve.

(如果您有来自世界各地的交易这可能会帮助您用作基础并不断改进。)

Private Function FromWorldTimeToMyLocalTime(noSpacesDateTimeTransaction As String, transactionZoneString As String) As Date
    Dim transactionDtTime As Date = Date.ParseExact(noSpacesDateTimeTransaction, "yyyyMMddHHmmss", Globalization.CultureInfo.InvariantCulture)
    Return DateAndTime.DateAdd(DateInterval.Hour, TimeZoneInfo.FindSystemTimeZoneById(transactionZoneString).BaseUtcOffset.TotalHours, transactionDtTime)
End Function

Usage (Here the example shows a transaction is done by Hawai):

(用法(此处示例显示交易是由Hawai完成的):)

 ‘Here is your complete string as you have in your xml tags (date + time) it’s presumed the transaction is come by  Hawai 
 Dim myDateTimeFromTransactionTime As String = FromWorldTimeToMyLocalTime("20191202234026", "Hawaiian Standard Time")
 Console.WriteLine("MyTime from transaction is " & myDateTimeFromTransactionTime)

To get all timezone infos you can use this to have an idea.

(要获取所有时区信息,您可以使用它来产生想法。)

Dim timeZones As ReadOnlyCollection(Of TimeZoneInfo) = TimeZoneInfo.GetSystemTimeZones()
For Each timeZoneInfo As TimeZoneInfo In timeZones
    Console.WriteLine(CStr(timeZoneInfo.Id) & "  " & CStr(timeZoneInfo.BaseUtcOffset.TotalHours))
Next

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...