【问题标题】:Convert the property value to yyyy-MM-dd hh:mm:ss tt format将属性值转换为 yyyy-MM-dd hh:mm:ss tt 格式
【发布时间】:2012-12-14 12:55:13
【问题描述】:

我有一个属性以下列方式保存日期时间信息

public string ExecutionTime{ get; set; }

ExecutionTime 值设置为dd-MM-yyyy hh:mm:ss tt
如何更改属性值以显示为 yyyy-MM-dd hh:mm:ss tt 并显示在 文本框 中。

【问题讨论】:

  • 您的属性是string 类型而不是DateTime 类型是否有原因?
  • 我确实在你身上看到了一个正确的观点。但它已经被设置并且它被用于许多其他文件中
  • 我不得不问:为什么不将其存储为 DateTime ?但是:有两种明显的方法可以解决这个问题:解析为DateTime,然后将其写入不同的格式,或者:只需针对不同的字符位置应用基本字符串重新映射

标签: c# asp.net .net c#-4.0 c#-3.0


【解决方案1】:

我不会使用string 属性。相反,我会将其存储为DateTime,因为它实际上似乎是一个。 当你显示它时,你可以随意格式化它

public DateTime ExecutionTime{ get; set; } 

例如:

Textbox1.Text = ExecutionTime.ToString("yyyy-MM-dd hh:mm:ss tt");

否则,您总是需要将该字符串解析为 DateTime,反之亦然,您甚至可能会遇到本地化问题(将来)。

【讨论】:

  • 请记住,格式字符串中冒号:的含义取决于当前区域性的TimeSeparator。例如,如果文化是"bn-IN"(印度的孟加拉语),它将写成05.13 而不是05:13。如果不需要,请在格式字符串中转义冒号,或使用不变的文化。
【解决方案2】:

因为您的日期存储为string

  1. 解析字符串得到实际的DateTime
  2. 用不同的格式转换回string

你需要ParseExact:

// Your date
string inputDate = "20-01-2012 02:25:50 AM";

// Converts to dateTime
// Do note that the InvariantCulture is used, as I've specified
// AM as the "tt" part of the date in the above example
DateTime theDate = DateTime.ParseExact(inputDate, "dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

// Now get the string to be displayed
// I've also specified the Invariant (US) culture, you might want something else
string yourString = theDate.ToString("yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);

但您确实应该将日期存储为DateTime,而不是string

【讨论】:

    【解决方案3】:
    DateTime d;
    var isValid = DateTime.TryParse(ExecutionTime, out d);
    if (isValid)
    {
        textBox1.Text = d.ToString("dd-MM-yyyy hh:mm:ss tt");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2016-11-06
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多