为了学习最佳实践,我有一个问题。在找到周日开始的方法时,我遇到了这个帖子。 “http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week”
问题:我需要4-3-2011的格式:有没有更有效的方法来实现这一点,而不是我的代码黑客攻击?
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
int ddt = dt.Day;
int mdt = dt.Month;
int ydt = dt.Year;
string sddt = ddt.ToString();
string smdt = mdt.ToString();
string sydt = ydt.ToString();
string fdate = (smdt + "-" + sddt + "-" + sydt);
线程代码:作者Sarcastic
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
答案 0 :(得分:11)
fdate = DateTime.Now.StartOfWeek(DayOfWeek.Sunday).ToString("M-d-yyyy");
在此处查看:Standard Date and Time Format Strings
,DateTimeFormatInfo
,用于格式化信息。
答案 1 :(得分:2)
更好?不确定。
对我来说第二个代码更好,那么你肯定可以使用
dt.ToString("d-m-yyyy");
答案 2 :(得分:1)
稍微好一点的扩展方法,将当前的文化考虑在内(from the same thread above):
public static class DateTimeExtensions {
public static DateTime StartOfWeek(this DateTime date) {
System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek dayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;
return date.AddDays(dayOfWeek - date.DayOfWeek);
}
}
然后使用:
DateTime.Now.StartOfWeek().ToString("M-d-yyyy");