gpt4 book ai didi

c# - 当客户端日历是非公历时,如何以公历格式获取 "DateTime.Now"?

转载 作者:行者123 更新时间:2023-11-30 14:35:16 25 4
gpt4 key购买 nike

当客户端日历不是公历时,如何在 公历 日历中获取 DateTime.Now

我的项目是一个带有 C# 代码的 Silverlight,并且未预测客户端默认日历。

最佳答案

日期时间值没有格式。在内部,它只是自 .NET 中的纪元 0001-01-01 00:00 以来的滴答计数。格式化是在您调用 ToString 时进行的。

只需为具有您想要的日历的文化使用不同的 CultureInfo,例如

CultureInfo french = CultureInfo.GetCultureInfo( "fr-FR" );

String nowStr = DateTime.Now.ToString( french );
Console.WriteLine( nowStr ); // "16/09/2012 05:58:00"

如果您只是想使用具有公历的可预测西方文化,请使用 CultreInfo.InvariantCulture

虽然 InvariantCulture is invariant它使用 en-USMM/dd/yyyy 日期格式,世界其他地方都不使用,所以我建议始终改为使用 ISO 8601...

将此代码复制到您的项目中:

using System;
using System.Globalization;

public static class CultureInfo2
{
/// <summary>A read-only clone of <see cref="P:System.Globalization.CultureInfo.InvariantCulture" />, except the <see cref="P:System.Globalization.CultureInfo.DateTimeFormat" /> is replaced with a <see cref="T:System.Globalization.DateTimeFormatInfo" /> configured to use ISO 8601 formatting for dates and times.</summary>
public static CultureInfo InvariantCultureWithIso8601 { get; } = CreateInvariantCultureWithIso8601();

private static CultureInfo CreateInvariantCultureWithIso8601()
{
CultureInfo obj = (CultureInfo)CultureInfo.InvariantCulture.Clone();
obj.DateTimeFormat = new DateTimeFormatInfo
{
AMDesignator = "AM",
DateSeparator = "-",
FirstDayOfWeek = DayOfWeek.Monday,
CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek,
FullDateTimePattern = "yyyy-MM-dd HH':'mm':'ss", // NOTE: Use `"yyyy-MM-DD'T'HH:mm:ss"` for stricter ISO 8601 compliance.
LongDatePattern = "yyyy-MM-dd ddd", // <-- This is subjective.
LongTimePattern = "HH':'mm':'ss",
MonthDayPattern = "MMMM dd",
PMDesignator = "PM",
ShortDatePattern = "yyyy-MM-dd",
ShortTimePattern = "HH:mm",
TimeSeparator = ":",
YearMonthPattern = "yyyy MMMM"
};
return CultureInfo.ReadOnly(obj);
}

public static String ToStringInvariant( this DateTime value )
{
return value.ToString( provider: InvariantCultureWithIso8601 );
}

public static String ToStringInvariant( this DateTime value, String format )
{
return value.ToString( format: format, provider: InvariantCultureWithIso8601 );
}
}

然后像这样使用它:

String nowStr = DateTime.Now.ToStringInvariant();
Console.WriteLine( nowStr ); // "2012-09-16 05:58:00"

关于c# - 当客户端日历是非公历时,如何以公历格式获取 "DateTime.Now"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com