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

发布于 2024-11-19 15:35:14 字数 239 浏览 0 评论 0原文

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

5/4/2011 |下午 2:06 | ... 应该是 05/04/2011 |下午 02:06 | ...

但是当我将其更改为不同的文化时,我希望它是

04.05.2011 | 14:06 | 14:06 ...

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

I know that I could use a format string, but I don't want to lose the culture specific representation of the date/time format. E.g.

5/4/2011 | 2:06 PM | ... should be 05/04/2011 | 02:06 PM | ...

But when I change it to a different culture, I want it to be

04.05.2011 | 14:06 | ...

without changing the format string. Is that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一抹苦笑 2024-11-26 15:35:14

您可以使用 DateTimeFormatInfo.CurrentInfo ShortDatePatternShortTimePattern 进行翻译:

// 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

You can use the DateTimeFormatInfo.CurrentInfo ShortDatePattern and ShortTimePattern to do the translation:

// 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
半葬歌 2024-11-26 15:35:14

这里的答案非常复杂。实际上,它就像简单一样

datetime.ToString("d", culture) // Short date
datetime.ToString("t", culture) // Short time

有关所有格式的完整列表以及示例输出,请参阅 https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-5.0

Really complicated answers here. In reality it's as simple as

datetime.ToString("d", culture) // Short date
datetime.ToString("t", culture) // Short time

For a full list of all formats with example outputs see https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-5.0.

梦里兽 2024-11-26 15:35:14

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

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;
        }

正如所承诺的,这里是改进的版本:

/// <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);
    }
}

I see only a single solution - you should obtain the current culture display format, patch it so that it meets your requirement and finally format your DateTime value using the patched format string. Here is some sample code:

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;
        }

As promised, here is the improved version:

/// <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);
    }
}
因为看清所以看轻 2024-11-26 15:35:14

您还可以重写 CurrentThread.CurrentCulture 类。在程序的开头,您可以调用此方法:

    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;
    }

通过此方法,您在程序中将日期显示为字符串的任何位置都将具有新的格式。

You could also override the CurrentThread.CurrentCulture class. At the beginning of your program you call this method:

    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;
    }

With this, anywhere you display a date as a string in your program it will have the new format.

铃予 2024-11-26 15:35:14

我写了一个方法来进行这种转换:

/// <summary>
/// Transform DateTime into short specified format
/// </summary>
/// <param name="strDateTime">string : input DateTime</param>
/// <param name="cultureInfo"></param>
/// <param name="strFormat">string - optional : ouput format - default "d"</param>
/// <returns></returns>
public static string ConvertDateTimeToShortDate(string strDateTime, CultureInfo cultureInfo, string strFormat="d")
{
  var dateTime = DateTime.MinValue;
  return DateTime.TryParse(strDateTime, out dateTime) ? dateTime.ToString(strFormat, cultureInfo) : strDateTime;
}

调用它,用于时间格式:

DateTimeTools.ConvertDateTimeToShortDate(DateTime.Today.ToString(),
            CultureInfo.InvariantCulture,"t");

希望它可以帮助你

I wrote a method to do that kind of transformations :

/// <summary>
/// Transform DateTime into short specified format
/// </summary>
/// <param name="strDateTime">string : input DateTime</param>
/// <param name="cultureInfo"></param>
/// <param name="strFormat">string - optional : ouput format - default "d"</param>
/// <returns></returns>
public static string ConvertDateTimeToShortDate(string strDateTime, CultureInfo cultureInfo, string strFormat="d")
{
  var dateTime = DateTime.MinValue;
  return DateTime.TryParse(strDateTime, out dateTime) ? dateTime.ToString(strFormat, cultureInfo) : strDateTime;
}

To call it, for time format :

DateTimeTools.ConvertDateTimeToShortDate(DateTime.Today.ToString(),
            CultureInfo.InvariantCulture,"t");

Hope it can help u

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文