从下拉选择的值中解析DateTime

时间:2014-05-14 19:38:50

标签: c# datetime

我从下拉列表中获取日期。 weekStartDate 中的日期格式为 12/05/2014 12:00:00 AM 。我希望它像 2014/05/12 12:00:00 AM

DateTime weekStartDate = Convert.ToDateTime(DrpDwnGetPayPeriod.SelectedValue);

下拉列表的值为2014年5月5日,2014年5月12日。当我尝试解析它时,我得到错误,因为String未被识别为有效的DateTime。 我试过以下:

DateTime weekStartDate = DateTime.ParseExact(DrpDwnGetPayPeriod.SelectedValue, "yyyy-MM-dd", CultureInfo.InvariantCulture);

5 个答案:

答案 0 :(得分:1)

Click this link for custom date time formatting

我认为你必须使用这样的函数:

DateTime.Today.ToString("YY/MM/DD HH:MM:SS TT")

答案 1 :(得分:1)

你的问题有点不清楚。但我假设你想知道“如何将某种格式的字符串转换为DateTime对象?”如果这不是你的问题,请澄清并意识到你需要在开始时让你的问题更清楚。

学习使用DateTime.ParseExact。并使用format strings。这给了我们......

DateTime weekStartDate = DateTime.ParseExact(DrpDwnGetPayPeriod.SelectedValue, "yyyy-MM-dd hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);

注意,您可能想要使用DateTime.TryParseExact。这将允许您处理与指定格式不匹配的值。

答案 2 :(得分:1)

使用标准格式"G"

weekStartDate.ToString("G"); //G: 12/5/2014 12:00:00 AM 

http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx

答案 3 :(得分:1)

您是否只想更改weekStartDate上的格式?你只需要沿着这些方向做点什么:

weekStartDate.ToString("yyyy/MM/dd hh:mm tt");

Here's an example

答案 4 :(得分:1)

  

下拉列表的值为2014年5月5日,2014年5月12日。当我尝试   解析它,我得到错误,因为String未被识别为有效   日期时间

所以这些是DropDownList

中的条目
05 May 2014
12 May 2014
21 Apr 2014

并且您希望将其解析为真实的DateTime

然后您可以使用DateTime.ParseExact

// presuming "21 Apr 2014" is DrpDwnGetPayPeriod.SelectedValue
DateTime weekStartDate = DateTime.ParseExact("21 Apr 2014", "dd MMM yyyy", CultureInfo.InvariantCulture);

由于您对月份名称使用三个字母缩写,因此需要使用MMM

MSDN:Custom Date and Time Format Strings