首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将.NET DateTimeFormatInfo转换为Javascript jQuery formatDate?

将.NET DateTimeFormatInfo转换为Javascript jQuery formatDate?
EN

Stack Overflow用户
提问于 2009-07-16 16:04:11
回答 4查看 6.3K关注 0票数 10

我有一个jQuery UI数据报警器,我打算在ASP.NET MVC中的文本框中使用它。textbox中的日期显示是通过CultureInfo本地化的,当然,jquery应该识别它以在datepicker中选择正确的日期:

代码语言:javascript
复制
<%= Html.TextBox("Date", Model.Date.ToString("d", currentCultureInfo),
    new { @class = "datepicker" })%>

我现在要做的是用如下所示的日期格式初始化数据报警器

代码语言:javascript
复制
string jsCode = @"$("".datepicker"").datepicker({
    dateFormat: '" + currentCultureInfo.DateTimeFormat.ShortDatePattern + @"',
});";

问题是,DateTimeFormatInfo的格式字符串(参见MSDN )的格式与jQuery (jQuery formatDate)中的格式字符串完全不同。

https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx

示例(德国日期格式,如16.07.2009):

代码语言:javascript
复制
.NET: 'dd.MM.yyyy' should be converted to 'dd.mm.yy' in jQuery/Javascript

是否有在两种格式之间进行所需转换的方法或库?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-08-09 20:19:34

如果只有ShortDatePattern必须转换,下面的代码提供了我需要的内容:

代码语言:javascript
复制
public class wxDateTimeConvert
{
    /// <summary>
    /// Gets the javascript short date pattern.
    /// </summary>
    /// <param name="dateTimeFormat">The date time format.</param>
    /// <returns></returns>
    public static string GetJavascriptShortDatePattern(DateTimeFormatInfo dateTimeFormat)
    {
        return dateTimeFormat.ShortDatePattern
            .Replace("M", "m")
            .Replace("yy", "y");
    }
}

包括页面中的Javascript:

代码语言:javascript
复制
    /// <summary>
    /// Inserts the localized datepicker jquery code
    /// </summary>
    private void InsertLocalizedDatepickerScript()
    {

        string dateformat = wxDateTimeConvert.GetJavascriptShortDatePattern(Thread.CurrentThread.CurrentUICulture.DateTimeFormat);
        String js = @"$(document).ready(function() {
$("".datepicker"").datepicker({
    changeYear: true,
    dateFormat: '" + dateformat + @"',
    maxDate: new Date()
  });
});";
        this.Page.Header.Controls.Add(
            new LiteralControl("<script type=\"text/javascript\">" + js + "</script>")
        );
    }

但是,这不处理月或日名称、时间格式或其他特殊情况。

票数 10
EN

Stack Overflow用户

发布于 2009-08-07 13:01:51

我刚刚遇到了完全相同的问题,并给出了下面的代码。它并不完美,但应该涵盖大多数文化,并优雅地失败。这可能也不是你能想出的最短版本!

代码语言:javascript
复制
///========================================================================
///  Method : ConvertDateFormat
/// 
/// <summary>
///   Takes a culture and returns matching C# and jQuery date format
///   strings. If possible the C# string will be the ShortDatePattern for
///   the supplied culture.
/// </summary>
///========================================================================
private static void GetDateFormats(CultureInfo xiCulture, out string xoCSharpFormat, out string xoJQueryFormat)
{
  //=======================================================================
  // Start by assigning formats that are hopefully unambiguous in case we
  // can't do better.
  //=======================================================================
  xoCSharpFormat = "yyyy-MM-dd";
  xoJQueryFormat = "yy-mm-dd";

  if (xiCulture.IsNeutralCulture)
  {
    try
    {
      xiCulture = CultureInfo.CreateSpecificCulture(xiCulture.Name);
    }
    catch
    {
      //===================================================================
      // Some cultures are neutral and don't have specific cultures.
      // There's not much we can do here.
      //===================================================================
      return;
    }
  }

  string lCSharpFormat = xiCulture.DateTimeFormat.ShortDatePattern;

  //=======================================================================
  // Handle:
  //  C#     jQuery  Meaning
  //  d      d       Day of month (no leading 0)
  //  dd     dd      Day of month (leading 0)
  //  M      m       Month of year (no leading 0)
  //  MM     mm      Month of year (leading 0)
  //  yy     y       Two digit year
  //  yyyy   yy      Not an exact match but good enough:
  //                 C# means: The year in four or five digits (depending on
  //                 the calendar used), including the century. Pads with
  //                 leading zeros to get four digits. Thai Buddhist and
  //                 Korean calendars have five-digit years. Users
  //                 selecting the "yyyy" pattern see all five digits
  //                 without leading zeros for calendars that have five
  //                 digits. Exception: the Japanese and Taiwan calendars
  //                 always behave as if "yy" is selected.
  //                 jQuery means: four digit year
  //
  //  Copy '.', '-', ' ', '/' verbatim
  //  Bail out if we find anything else and return standard date format for
  //  both.
  //=======================================================================
  StringBuilder lJQueryFormat = new StringBuilder();
  bool lError = false;
  for (int ii = 0; ii < lCSharpFormat.Length; ++ii)
  {
    Char lCurrentChar = lCSharpFormat[ii];

    switch (lCurrentChar)
    {
      case 'd':
        //=================================================================
        // d or dd is OK, ddd is not
        //=================================================================
        if (ii < (lCSharpFormat.Length - 1) &&
          lCSharpFormat[ii+1] == 'd')
        {
          if (ii < (lCSharpFormat.Length - 2) &&
          lCSharpFormat[ii+2] == 'd')
          {
            //=============================================================
            // ddd
            //=============================================================
            lError = true;
          }
          else
          {
            //=============================================================
            // dd
            //=============================================================
            lJQueryFormat.Append("dd");
            ii++;
          }
        }
        else
        {
          //===============================================================
          // d
          //===============================================================
          lJQueryFormat.Append('d');
        }
        break;
      case 'M':
        //=================================================================
        // M or MM is OK, MMM is not
        //=================================================================
        if (ii < (lCSharpFormat.Length - 1) &&
          lCSharpFormat[ii + 1] == 'M')
        {
          if (ii < (lCSharpFormat.Length - 2) &&
          lCSharpFormat[ii + 2] == 'M')
          {
            //=============================================================
            // MMM
            //=============================================================
            lError = true;
          }
          else
          {
            //=============================================================
            // MM
            //=============================================================
            lJQueryFormat.Append("mm");
            ii++;
          }
        }
        else
        {
          //===============================================================
          // M
          //===============================================================
          lJQueryFormat.Append('m');
        }
        break;
      case 'y':
        //=================================================================
        // yy or yyyy is OK, y, yyy, or yyyyy is not
        //=================================================================
        if (ii < (lCSharpFormat.Length - 1) &&
          lCSharpFormat[ii + 1] == 'y')
        {
          if (ii < (lCSharpFormat.Length - 2) &&
            lCSharpFormat[ii + 2] == 'y')
          {
            if (ii < (lCSharpFormat.Length - 3) &&
              lCSharpFormat[ii + 3] == 'y')
            {
              if (ii < (lCSharpFormat.Length - 4) &&
                lCSharpFormat[ii + 4] == 'y')
              {
                //=========================================================
                // yyyyy
                //=========================================================
                lError = true;
              }
              else
              {
                //=========================================================
                // yyyy
                //=========================================================
                lJQueryFormat.Append("yy");
                ii = ii + 3;
              }
            }
            else
            {
              //===========================================================
              // yyy
              //===========================================================
              lError = true;
            }
          }
          else
          {
            //=============================================================
            // yy
            //=============================================================
            lJQueryFormat.Append("y");
            ii++;
          }
        }
        else
        {
          //===============================================================
          // y
          //===============================================================
          lError = true;
        }
        break;
      case '.':
      case '-':
      case ' ':
      case '/':
        lJQueryFormat.Append(lCurrentChar);
        break;
      default:
        lError = true;
        break;
    }

    if (lError)
    {
      break;
    }
  }

  //=======================================================================
  // If we didn't get an error return the culture specific formats
  //=======================================================================
  if (!lError)
  {
    xoCSharpFormat = lCSharpFormat;
    xoJQueryFormat = lJQueryFormat.ToString();
  }
}
票数 6
EN

Stack Overflow用户

发布于 2009-08-07 13:22:28

我想这是最简单的方法..。

代码语言:javascript
复制
string dateFormat = currentCultureInfo.DateTimeFormat.ShortDatePattern.Replace("MM", "mm");
string jsCode = @"$("".datepicker"").datepicker({
    dateFormat: '" + dateFormat + @"',
});";
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1138635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档