System.FormatException: 字符串 ‘638143033743100000’ 无法识别为有效的 DateTime。

huangapple go评论80阅读模式
英文:

System.FormatException: String '638143033743100000' was not recognized as a valid DateTime

问题

错误:

System.FormatException: 字符串 '638143033743100000' 未被识别为有效的 DateTime

当前代码已经有允许两种不同日期格式的处理方式:

items = (await itemService.GetItems())
       .GroupBy(x => x.ItemKey)
       .Select(x => new DisplayItem
       {
           item = x.item,            
           country = x.FirstOrDefault(y => y.item == "Country")?.Value,             
           date = x.FirstOrDefault(y => y.item == "Date")?.Value != null
           ? DateTime.ParseExact(x.FirstOrDefault(y => y.item == "Date")?.Value, 
           new string[] {
            "yyyy-MM-dd HH:mm:ss.FFFFFFF",
            "dd.MM.yyyy HH:mm:ss"}, null, DateTimeStyles.AssumeLocal)
           : (DateTime?)null
       }).Where(s => s.country!= null).OrderByDescending(s => s.date).ToList();       

我们已经添加了一个新的日期格式,现在使用的是时间戳。我能知道时间戳的格式吗?谢谢。

英文:

Error:

System.FormatException: String '638143033743100000' was not recognized as a valid DateTime

Current code already has provision to allow two different date format:

items = (await itemService.GetItems())
       .GroupBy(x => x.ItemKey)
       .Select(x => new DisplayItem
       {
           item = x.item,            
           country = x.FirstOrDefault(y => y.item == "Country")?.Value,             
           date = x.FirstOrDefault(y => y.item == "Date")?.Value != null
           ? DateTime.ParseExact(x.FirstOrDefault(y => y.item == "Date")?.Value, 
           new string[] {
            "yyyy-MM-dd HH:mm:ss.FFFFFFF",
            "dd.MM.yyyy HH:mm:ss"}, null, DateTimeStyles.AssumeLocal)
           : (DateTime?)null
       }).Where(s => s.country!= null).OrderByDescending(s => s.date).ToList();       

We have added a new date format. Using time in ticks now. May I know the format for ticks. Thank you.

答案1

得分: 2

To convert from string ticks to DateTime, parse it as a long and use the following:

long ticks = 638143033743100000L;
DateTime dt = new DateTime(ticks);

And here is how you can use it in your code:

items = (await itemService.GetItems())
       .GroupBy(x => x.ItemKey)
       .Select(x => new DisplayItem
       {
           item = x.item,            
           country = x.FirstOrDefault(y => y.item == "Country")?.Value,             
           date = (x.FirstOrDefault(y => y.item == "Date") != null) && long.TryParse(x.FirstOrDefault(y => y.item == "Date").Value, out long l) && l > 0
           ? new DateTime(l) : (DateTime?)null
       }).Where(s => s.country!= null).OrderByDescending(s => s.date).ToList();

You can then set the formatting on your property date later down the line.

英文:

EDIT: Didn't see it was in ticks and not in UnixTime

To convert from string ticks to DateTime, parse it as a long and use the following

long ticks = 638143033743100000L;
DateTime dt = new(ticks);

Here is a working fiddle

And here is how you can use it in your code

items = (await itemService.GetItems())
   .GroupBy(x => x.ItemKey)
   .Select(x => new DisplayItem
   {
       item = x.item,            
       country = x.FirstOrDefault(y => y.item == "Country")?.Value,             
       date = (x.FirstOrDefault(y => y.item == "Date") != null) && long.TryParse(x.FirstOrDefault(y => y.item == "Date").Value, out long l) && l > 0
       ? new DateTime(l) : (DateTime?)null
   }).Where(s => s.country!= null).OrderByDescending(s => s.date).ToList();  

You can then set the formatting on your property date later down the line.


Original answer:

Here is how to convert a Timestamp to a DateTime

First, convert your string to a long

If it is in seconds

DateTimeOffset.FromUnixTimeSeconds(long).UtcDateTime

If it is in milliseconds

DateTimeOffset.FromUnixTimeMilliseconds(l).UtcDateTime;

It if better to make an extension method

public static class NumericExtensions
{
    public static DateTime ConvertFromTimestampSecondsToDateTime(this long l) => DateTimeOffset.FromUnixTimeSeconds(l).UtcDateTime;
    public static DateTime ConvertFromTimestampMillisecondsToDateTime(this long l) => DateTimeOffset.FromUnixTimeMilliseconds(l).UtcDateTime;
}

Then use them like so

long timestamp = 638143033743100000l;
DateTime dt = timestamp.ConvertFromTimestampMillisecondsToDateTime();

答案2

得分: 2

Sure, here's the translated code portion:

创建一个新方法,而不是直接使用 ParseExact,然后调用该方法。这将使您的代码更加可读。在 LINQ 语句中处理空值情况会导致维护问题。

.Select(x => new DisplayItem
{
    item = x.item,
    country = x.FirstOrDefault(y => y.item == "Country")?.Value,
    date = MyLovelyDateTimeParse(x.FirstOrDefault(y => y.item == "Date")?.Value),
    // ...... 其他部分
})

public DateTime? MyLovelyDateTimeParse(string dateString)
{
    if (String.IsNullOrEmpty(dateString))
        return null;
    else if (long.TryParse(dateString, out long value))
        return new DateTime(value);
    else
        return DateTime.ParseExact(dateString,
            new string[] {
            "yyyy-MM-dd HH:mm:ss.FFFFFFF",
            "dd.MM.yyyy HH:mm:ss"}, null, DateTimeStyles.AssumeLocal);
}

Please note that I have translated the code part only as per your request. If you have any further questions or need additional assistance, feel free to ask.

英文:

Create a new method and use that instead of ParseExact directly and call that instead. Should make your code even more readable. Your handling of null cases in the midth of the linq statement is a maintenance mess.

.Select(x => new DisplayItem
   {
       item = x.item,            
       country = x.FirstOrDefault(y => y.item == "Country")?.Value,             
       date = MyLovelyDateTimeParse(x.FirstOrDefault(y => y.item == 
       "Date")?.Value),
       ...... etc.
   })



public DateTime? MyLovelyDateTimeParse(string dateString)
{
	if (String.IsNullOrEmpty(dateString))
		return null;
	else if (long.TryParse(dateString, out long value))
		return new DateTime(value);
	else
		return DateTime.ParseExact(dateString,
			new string[] {
			"yyyy-MM-dd HH:mm:ss.FFFFFFF",
			"dd.MM.yyyy HH:mm:ss"}, null, DateTimeStyles.AssumeLocal);			
}

huangapple
  • 本文由 发表于 2023年4月19日 21:49:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定