.net 如何在没有工作日的情况下从 DateTime 获取长日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1395022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a Long Date format from DateTime without a weekday
提问by Adam Tegen
I'm looking for a locale-aware way of acquiring a long date time without the weekday. Just such a beast exist?
我正在寻找一种区域设置感知方式来获取没有工作日的长日期时间。就存在这样的野兽?
Below is the code I use to get the long date format including the weekday:
下面是我用来获取包括工作日在内的长日期格式的代码:
DateTime time = ...
String formattedDate = time.ToLongDateString();
Edit
编辑
Examples of what I would like to see:
我想看到的例子:
- en-us: December 5, 2009
- fr-fr: 5 décembre 2009
- es-es: 05 de diciembre de 2009
- zh-cn: 2009 年 12 月 5 日
- fr-fr:2009 年 12 月 5 日
- es-es: 05 de diciembre de 2009
ToLongDateString() returns the following:
ToLongDateString() 返回以下内容:
- en-us: Saturday, December 5, 2009
- fr-fr: samedi 5 décembre 2009
- es-es: sábado, 05 de diciembre de 2009
- en-us:2009 年 12 月 5 日,星期六
- fr-fr:samedi 2009 年 12 月 5 日
- es-es: sábado, 05 de diciembre de 2009
采纳答案by Adam Tegen
This seemed to do the trick.
这似乎奏效了。
- Enumerate all valid datetime patterns: CultureInfo.DateTimeFormat.GetAllDateTimePatterns
- Select longest pattern (presumably this is the best match) that:
- Is a substring of the CultureInfo.DateTimeFormat.LongDatePattern
- Does not contain "ddd" (short day name)
- Does not contain "dddd" (long day name)
- 枚举所有有效的日期时间模式: CultureInfo.DateTimeFormat.GetAllDateTimePatterns
- 选择最长的模式(大概这是最好的匹配):
- 是 CultureInfo.DateTimeFormat.LongDatePattern 的子字符串
- 不包含“ddd”(简称日名)
- 不包含“dddd”(长日名)
This appears to come up with the strings I was looking for.
这似乎是我正在寻找的字符串。
See code below:
见下面的代码:
class DateTest
{
static private string GetDatePatternWithoutWeekday(CultureInfo cultureInfo)
{
string[] patterns = cultureInfo e.DateTimeFormat.GetAllDateTimePatterns();
string longPattern = cultureInfo.DateTimeFormat.LongDatePattern;
string acceptablePattern = String.Empty;
foreach (string pattern in patterns)
{
if (longPattern.Contains(pattern) && !pattern.Contains("ddd") && !pattern.Contains("dddd"))
{
if (pattern.Length > acceptablePattern.Length)
{
acceptablePattern = pattern;
}
}
}
if (String.IsNullOrEmpty(acceptablePattern))
{
return longPattern;
}
return acceptablePattern;
}
static private void Test(string locale)
{
DateTime dateTime = new DateTime(2009, 12, 5);
Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);
string format = GetDatePatternWithoutWeekday(Thread.CurrentThread.CurrentCulture);
string result = dateTime.ToString(format);
MessageBox.Show(result);
}
}
Technically, it probably wouldn't work if a long format had the name of the day sandwiched in the middle. For that, I should choose the pattern with longest common substring instead of longest exact match.
从技术上讲,如果长格式将日期的名称夹在中间,它可能不会起作用。为此,我应该选择具有最长公共子串的模式而不是最长的精确匹配。
回答by Reza
String formattedDate = DateTime.Now.Date.ToLongDateString().Replace(DateTime.Now.DayOfWeek.ToString()+ ", ", "")
回答by user7116
A very awful, horrible way to accomplish this is to remove the format specifiers you don't want from the existing LongDatePattern:
实现此目的的一种非常糟糕、可怕的方法是从现有的 LongDatePattern 中删除您不想要的格式说明符:
public static string CorrectedLongDatePattern(CultureInfo cultureInfo)
{
var info = cultureInfo.DateTimeFormat;
// This is bad, mmmkay?
return Regex.Replace(info.LongDatePattern, "dddd,?",String.Empty).Trim();
}
回答by David Rutten
If the LongDate sequence is also culture specific, then I'm afraid you're out of luck and you'll have to write actual code for this. Otherwise, a collection of formatting tagswill do the trick.
如果 LongDate 序列也是特定于文化的,那么恐怕您不走运,您必须为此编写实际代码。否则,一组格式化标签就可以解决问题。
I'm afraid what you'll have to do is create an array of 7 strings (one for each day) in the local culture, and remove those strings from your LongDate format output. Then make sure you remove all duplicated /'s -'s and spaces.
恐怕您必须做的是在当地文化中创建一个包含 7 个字符串(每天一个)的数组,然后从 LongDate 格式输出中删除这些字符串。然后确保删除所有重复的 / 的 - 和空格。
Hope there's a better way but I don't see it.
希望有更好的方法,但我没有看到。
回答by VDWWD
This is an improved answer from Reza, which does not work correctly with some localizations.
这是 Reza 的改进答案,它在某些本地化中无法正常工作。
string formattedDate = DateTime.Now.ToLongDateString().Replace(System.Globalization.DateTimeFormatInfo.CurrentInfo.GetDayName(DateTime.Now.DayOfWeek), "").TrimStart(", ".ToCharArray());
回答by Curt
This is an old, old thead, but I came across it because it perfectly matched the use case I needed to solve. I ended up writing a piece of code that works, so I thought I'd include it for those that need it. (It has a few extra tricks, like defaulting to the current date, and allowing either the full date string for a culture, or one with the day-of-the-week removed):
这是一个古老的老头,但我遇到了它,因为它与我需要解决的用例完美匹配。我最终编写了一段有效的代码,所以我想我会把它包含在那些需要它的人中。(它有一些额外的技巧,例如默认为当前日期,并允许区域性的完整日期字符串,或删除星期几的字符串):
public string DateString(DateTime? pDt = null, string lang, bool includeDayOfWeek = true)
{
if (pDt == null) pDt = DateTime.Now;
DateTime dt = (DateTime)pDt;
System.Globalization.CultureInfo culture = null;
try { culture = new System.Globalization.CultureInfo(lang); }
catch{ culture = System.Globalization.CultureInfo.InvariantCulture; }
string ss = dt.ToString("D", culture);
if (!includeDayOfWeek)
{
// Find day-of-week string, and remove it from the date string
// (including any trailing spaces or punctuation)
string dow = dt.ToString("dddd", culture);
int len = dow.Length;
int pos = ss.IndexOf(dow);
if (pos >= 0)
{
while ( ((len + pos) < ss.Length) && ( !Char.IsLetterOrDigit(ss[len+pos])))
len++;
ss = ss.Substring(0, pos) + ss.Substring(len+pos, ss.Length - (len+pos));
}
}
return ss;
}
回答by Frank Smith
I have expanded on the suggestion by Bart Calixto to fix the dd MMM yyyy format issue (here in Australia we also use UK date format dd/mm/yy)
我已经扩展了 Bart Calixto 的建议,以修复 dd MMM yyyy 格式问题(在澳大利亚,我们也使用英国日期格式 dd/mm/yy)
I also frequently need to convert between Aust and US date formats.
我还经常需要在 Aust 和 US 日期格式之间进行转换。
This code fixes the problem (my version is in VB)
这段代码解决了这个问题(我的版本是 VB)
Public Shared Function ToLongDateWithoutWeekDayString(source As DateTime, cult As System.Globalization.CultureInfo) As String
Return source.ToString("D", cult).Replace(source.DayOfWeek.ToString(), "").Trim(","c, " "c)
End Function
Before calling the function you need to set culture, I do it this way after getting the visitor's country from http://ipinfo.io
在调用需要设置文化的函数之前,我是从http://ipinfo.io获取访问者的国家后这样做的
Select Case Country.country
Case "AU"
cult = New CultureInfo("en-AU")
Case "US"
cult = New CultureInfo("en-US")
Case "GB"
cult = New CultureInfo("en-GB")
End Select
Dim date1 As New Date(2010, 8, 18)
lblDate.Text = ToLongDateWithoutWeekDayString(date1, cult)
After setting AU or GB culture result is 18 August 2010
设置 AU 或 GB 文化后,结果为 2010 年 8 月 18 日
After setting US culture result is August 18, 2010
设置美国文化后结果为2010年8月18日
Adam do you agree this solves the formatting issue you refer to?
亚当你同意这解决了你提到的格式问题吗?
Thanks Bart that was very nice code.
谢谢巴特,这是非常好的代码。
Dont forget to add Dim cult As System.Globalization.CultureInfoafter
Inherits System.Web.UI.Page
不要忘记Dim cult As System.Globalization.CultureInfo在继承 System.Web.UI.Page 之后添加
回答by Frank Smith
My solution:
我的解决方案:
DateTime date = DateTime.Now;
CultureInfo culture = CultureInfo.CurrentCulture;
string dayName = date.ToString("dddd", culture);
string fullDate = date.ToString("f", culture);
string trim = string.Join(" ", fullDate.Replace(dayName, "").TrimStart(',').TrimStart(' ').Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
The last line:
最后一行:
- Removes leftover comma at start
- Removes leftover space at start
- Removes leftover double-space from anywhere in the string
- 在开始时删除剩余的逗号
- 在开始时删除剩余空间
- 从字符串中的任何位置删除剩余的双空格
Tested for each culture from
对每种文化进行了测试
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
回答by franzo
Improving on the accepted answer, GetAllDateTimePatternscan take a parameter to restrict the result to patterns relating to a standard format string, such as 'D' for the long date pattern.
改进已接受的答案,GetAllDateTimePatterns可以使用参数将结果限制为与标准格式字符串相关的模式,例如长日期模式的“D”。
For example, GetAllDateTimePatterns('D')is currently returning this for en-US:
例如,GetAllDateTimePatterns('D')目前正在为 en-US 返回此内容:
"dddd, MMMM d, yyyy", "MMMM d, yyyy", "dddd, d MMMM, yyyy", "d MMMM, yyyy"
and this for zh-HK:
这对于zh-HK:
"yyyy'年'M'月'd'日'", "yyyy'年'MM'月'dd'日'", "yyyy年MMMd日", "yyyy年MMMd日, dddd"
Assuming they're listed in some order of preference or prevalence, we can select the first option that does not contain the day of the week.
假设它们以某种偏好或流行顺序列出,我们可以选择不包含星期几的第一个选项。
Here are extension methods so you can simply use myDateTime.ToLongDateStringWithoutDayOfWeek()and myDateTime.ToLongDateTimeStringWithoutDayOfWeek().
这是扩展方法,因此您可以简单地使用myDateTime.ToLongDateStringWithoutDayOfWeek()和myDateTime.ToLongDateTimeStringWithoutDayOfWeek()。
public static string ToLongDateStringWithoutDayOfWeek(this DateTime d)
{
return d.ToString(
CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns('D')
.FirstOrDefault(a => !a.Contains("ddd") && !a.Contains("dddd"))
?? "D");
}
public static string ToLongDateTimeStringWithoutDayOfWeek(this DateTime d, bool includeSeconds = false)
{
char format = includeSeconds ? 'F' : 'f';
return d.ToString(
CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(format)
.FirstOrDefault(a => !a.Contains("ddd") && !a.Contains("dddd"))
?? format.ToString());
}
回答by itsclarke
Why not get the LongDate and trim off the first portion where the weekday appears?
为什么不获取 LongDate 并修剪出现工作日的第一部分?
DateTime date = Convert.ToDateTime(content["DisplayDate"]);
//-->3/15/2016 2:09:13 PM
string newDate = date.ToString("D", new CultureInfo("es-ES"));
//--> martes, 15 de marzo de 2016
var index = newDate.IndexOf(",") + 1;
//--> 7
string finalDate = newDate.Substring(index);
//--> 15 de marzo de 2016

