【问题标题】:How do I change 1 date format to another in C# e.g 10/10/2014 to 2014-10-10 (Year-month-day)?如何在 C# 中将 1 个日期格式更改为另一种日期格式,例如 10/10/2014 到 2014-10-10(年-月-日)?
【发布时间】:2014-12-19 00:32:55
【问题描述】:

如何在 C# 中将一种日期格式更改为另一种日期格式,例如 10/10/2014 到 2014-10-10(年-月-日)?

用户使用日期选择器选择一个日期,然后它出现在文本框中,但格式为 10/10/2014(日/月/年)。但我需要将此输出转换为反映这种格式 2014-10-10 (Year-month-day)

在 asp.net-mvc 中

代码:

@Html.Label("Start", "Start Date:")
@Html.TextBox("Start", string.Empty, new {@id = "Start", @class = "datepicker"})
@Html.Label("endd", "End Date:")
@Html.TextBox("endd", string.Empty, new {@id = "End", @class = "datepicker"})
<input type="submit" value="Apply" id ="DateSelected" />

【问题讨论】:

  • 这看起来像asp.net-mvc。您是否尝试过格式化您的 DateTime 值?
  • 在asp.net-mvc中。
  • 您使用的是哪个日期选择器库?
  • 来自 jqueryui 的那个

标签: c# html asp.net asp.net-mvc date


【解决方案1】:

对于 c# 的转换将是:

public static string convert(string dateValue){
        string pattern = "MM/dd/yyyy";
        DateTime parsedDate; 
        if (DateTime.TryParseExact(dateValue, pattern, null, 
                                   DateTimeStyles.None, out parsedDate)){
            return String.Format("{0:yyyy-MM-dd}",parsedDate);
        }
        return null;
    }

    //usage example
        string dateValue="10/10/2014";
        string converted=convert(dateValue);
        if(converted!=null){
            Console.WriteLine("Converted '{0}' to {1}.", 
                                  dateValue, converted); 
        } 

【讨论】:

    【解决方案2】:

    jQuery UI datepicker documentation 设置日期选择器时,指定格式:

    $( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-25
      • 2019-06-15
      • 1970-01-01
      • 2019-09-08
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多