C# 将字符串格式化为日期

标签 c# datetime string-formatting

<分区>

我有一个 DetailsView,其中一个 TextBox 绑定(bind)到 DateTime 列。该列的值以“dd/mm/yyyy hh:mm:ss”格式显示。我需要它以“yyyy/mm/dd”格式显示。我认为最好的方法可能是在 DataBound 事件中格式化字符串。问题是,我似乎找不到将字符串格式化为日期的方法。 String.Format 不会这样做。如果我将字符串作为 DateTime,那么我可以使用 DateTime.Format 方法。我可以通过解析字符串的各种元素来创建日期时间变量,但我不禁认为一定有更简单的方法吗?

谢谢

罗布。

最佳答案

像这样的东西应该可以工作:

public static string GetDateString(string date)
{
    DateTime theDate;
    if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss", 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
    {
        // the string was successfully parsed into theDate
        return theDate.ToString("yyyy'/'MM'/'dd");
    }
    else
    {
        // the parsing failed, return some sensible default value
        return "Couldn't read the date";
    }
}

关于C# 将字符串格式化为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3521119/

相关文章:

c# - 用四位数填充字符串

haskell - printf 字符串列表

c# - 为什么 TextRenderer.MeasureText 不能在 C# 中使用较大的字体正确测量文本?

c# - 如何使用 javascript 运行 C# 命令?

c# - 日期时间.TryParse -> "Ghost ticks"

MySQL日期格式转换 "Fri, 06 Nov 2015 04:06:05 -0500"

javascript - JavaScript 中的字符串格式

c# - 使用 Pdftron 在 C# 中将 Excel 转为 Pdf

c# - 如何将我的 Microsoft SQL Server 2016 数据库附加到 Visual Studio 2015 中的 installshield 项目?

javascript - 不同格式的日期时间的转换和比较