首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有没有一种文化安全的方法来获取带有前导零的ToShortDateString()和ToShortTimeString()?

有没有一种文化安全的方法来获取带有前导零的ToShortDateString()和ToShortTimeString()?
EN

Stack Overflow用户
提问于 2011-07-12 02:26:23
回答 5查看 13.7K关注 0票数 20

我知道我可以使用格式字符串,但我不想丢失日期/时间格式的特定于文化的表示。例如。

5/4/2011 | 2:06 PM | ...应为05/04/2011 | 02:06 PM | ...

但是当我把它改变成不同的文化时,我希望它是

04.05.2011 | 14:06 | ...

而不改变格式字符串。这有可能吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-07-12 02:29:29

我只看到一个解决方案--您应该获取当前的区域性显示格式,对其进行修补以满足您的需求,最后使用修补后的格式字符串来格式化您的DateTime值。下面是一些示例代码:

代码语言:javascript
复制
string pattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
        DateTime dt = DateTime.Now;
        string[] format = pattern.Split(new string[] { CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator }, StringSplitOptions.None);
        string newPattern = string.Empty;
        for(int i = 0; i < format.Length; i++) {
            newPattern = newPattern + format[i];
            if(format[i].Length == 1)
                newPattern += format[i];
            if(i != format.Length - 1)
                newPattern += CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
        }

正如承诺的那样,以下是改进后的版本:

代码语言:javascript
复制
/// <summary>
/// Extensions for the <see cref="DateTime"/> class.
/// </summary>
public static class DateTimeExtensions
{
    /// <summary>
    /// Provides the same functionality as the ToShortDateString() method, but
    /// with leading zeros.
    /// <example>
    /// ToShortDateString: 5/4/2011 |
    /// ToShortDateStringZero: 05/04/2011
    /// </example>
    /// </summary>
    /// <param name="source">Source date.</param>
    /// <returns>Culture safe short date string with leading zeros.</returns>
    public static string ToShortDateStringZero(this DateTime source)
    {
        return ToShortStringZero(source,
            CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern,
            CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator);
    }

    /// <summary>
    /// Provides the same functionality as the ToShortTimeString() method, but
    /// with leading zeros.
    /// <example>
    /// ToShortTimeString: 2:06 PM |
    /// ToShortTimeStringZero: 02:06 PM
    /// </example>
    /// </summary>
    /// <param name="source">Source date.</param>
    /// <returns>Culture safe short time string with leading zeros.</returns>
    public static string ToShortTimeStringZero(this DateTime source)
    {
        return ToShortStringZero(source,
            CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern,
            CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator);
    }

    private static string ToShortStringZero(this DateTime source, 
        string pattern,
        string seperator)
    {
        var format = pattern.Split(new[] {seperator}, StringSplitOptions.None);

        var newPattern = string.Empty;

        for (var i = 0; i < format.Length; i++)
        {
            newPattern = newPattern + format[i];
            if (format[i].Length == 1)
                newPattern += format[i];
            if (i != format.Length - 1)
                newPattern += seperator;
        }

        return source.ToString(newPattern, CultureInfo.InvariantCulture);
    }
}
票数 8
EN

Stack Overflow用户

发布于 2011-07-12 02:54:07

您可以使用DateTimeFormatInfo.CurrentInfo ShortDatePatternShortTimePattern进行转换:

代码语言:javascript
复制
// Change the culture to something different
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-AT");
DateTime test_datetime = new DateTime(2008, 10, 2, 3, 22, 12);
string s_date = test_datetime.ToString(DateTimeFormatInfo.CurrentInfo);

// For specifically the short date and time
string s_date1 = 
   test_datetime.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern);
string s_time1 = 
   test_datetime.ToString(DateTimeFormatInfo.CurrentInfo.ShortTimePattern);

// Results
// s_date1 == 02.10.2008
// s_time1 == 03:22
票数 18
EN

Stack Overflow用户

发布于 2011-07-12 02:56:33

您还可以覆盖CurrentThread.CurrentCulture类。在程序开始时,您可以调用此方法:

代码语言:javascript
复制
    private void FixCurrentDateFormat()
    {
        var cc = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        var df = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
        df.FullDateTimePattern = PatchPattern(df.FullDateTimePattern);
        df.LongDatePattern = PatchPattern(df.LongDatePattern);
        df.ShortDatePattern = PatchPattern(df.ShortDatePattern);
        //change any other patterns that you could use

        //replace the current culture with the patched culture
        System.Threading.Thread.CurrentThread.CurrentCulture = cc;
    }

    private string PatchPattern(string pattern)
    {
        //modify the pattern to your liking here
        //in this example, I'm replacing "d" with "dd" and "M" with "MM"
        var newPattern = Regex.Replace(pattern, @"\bd\b", "dd");
        newPattern = Regex.Replace(newPattern, @"\bM\b", "MM");
        return newPattern;
    }

这样,在程序中将日期显示为字符串的任何地方,它都将具有新的格式。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6654695

复制
相关文章

相似问题

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