我有一個來自表單服務器的時間戳20220505 17:36:29- 它有 2 個空格,我不相信發件人在未來的修訂版中總是發送相同數量的空格 - 理想情況下,我希望同樣處理任意數量的空格。
我試過這個DateTime.ParseExact但失敗了:
var horribleTimestamp = "20220505 17:36:29";
var timestamp = DateTime.ParseExact(horribleTimestamp, "yyyyMMdd hh:mm:ss", CultureInfo.InvariantCulture)
// throws `System.FormatException: String '20220505 17:36:29' was not recognized as a valid DateTime.`
為了避免我以后對時區的頭痛,我怎樣才能做到這一點,Nodatime因為我認為切換到那個是有意義的。
我的 PC 上的時間是本地時間,我想將其轉換為給定本地時區的全域時間戳(我認為應該是即時的?)?
uj5u.com熱心網友回復:
如果要處理任意數量的空格,有兩種選擇:
- 使用正則運算式(或類似運算式)將其轉換為具有單個空格的規范格式
- 拆分空格,然后分別決議第一個和最后一個部分。(或按空格分割,重新組合第一個和最后一個部分并決議......)
在 Noda Time 中,您獲得的值表示 a LocalDateTime,因此您應該將其決議為。這是使用正則運算式方法的完整示例:
using NodaTime;
using NodaTime.Text;
using System.Text.RegularExpressions;
// Lots of spaces just to check the canonicalization
string text = "20220505 17:36:29";
// Replace multiple spaces with a single space.
string canonicalized = Regex.Replace(text, " ", " ");
// Note: patterns are immutable; you should generally store them in
// static readonly fields. Note that "uuuu" represents an absolute year number,
// whereas "yyyy" would be "year of era".
LocalDateTimePattern pattern =
LocalDateTimePattern.CreateWithInvariantCulture("uuuuMMdd HH:mm:ss");
ParseResult<LocalDateTime> result = pattern.Parse(canonicalized);
// Note: if you're happy with an exception being thrown on a parsing failure,
// juse use result.Value unconditionally. The approach below shows what to do
// if you want to handle parse failures without throwing an exception (or with
// extra behavior).
if (result.Success)
{
LocalDateTime value = result.Value;
Console.WriteLine(value);
}
else
{
// You can also access an exception with more information
Console.WriteLine("Parsing failed");
}
uj5u.com熱心網友回復:
您可以將多種格式ParseExact作為陣列傳遞
var horribleTimestamp = "20220505 17:36:29";
var formats = new[]{"yyyyMMdd HH:mm:ss","yyyyMMdd HH:mm:ss","yyyyMMdd HH:mm:ss"};
var timestamp = DateTime.ParseExact(horribleTimestamp, formats, CultureInfo.InvariantCulture, 0);
dotnetfiddle
uj5u.com熱心網友回復:
您的格式有誤。使用 HH 代替 hh。請參閱下面的更新代碼
var horribleTimestamp = "20220505 17:36:29";
var timestamp = DateTime.ParseExact(horribleTimestamp, "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture)
這是 y 鏈接,它解釋了您可以在格式中使用的內容 - > https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
uj5u.com熱心網友回復:
您可以通過以下方式解決空格問題:
var horribleTimestamp = "20220505 17:36:29";
var date = horribleTimestamp.Substring(0, 8);
var index = horribleTimestamp.LastIndexOf(' ') 1;
var time = horribleTimestamp.Substring(index, horribleTimestamp.Length - index);
var timestamp = DateTime.ParseExact($"{date} {time}", "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture);
我想那個日期總是有 8 個字符并且那個空格總是存在的。在其他情況下,檢查索引 == -1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472604.html
上一篇:將欄位轉換為日期會給出日期時間值
