Is there a better way to deconstruct a date?

In an attempt to learn best practices, I have a question. While working to find the beginning of the week, I came across this topic. "Http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week"

Question: I need a 4-3-2011 format: is there a more efficient way to accomplish this, unlike my hacking code?

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

Topic Code: Posted by 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); 
+4
source share
3 answers
 fdate = DateTime.Now.StartOfWeek(DayOfWeek.Sunday).ToString("Md-yyyy"); 

see here Standard Date and Time Format Strings , DateTimeFormatInfo for formatting information.

+11
source

it is better? not sure.

The second code is better for me, then you can just use

 dt.ToString("dm-yyyy"); 
+2
source

A slightly better expansion method allows for the current culture (from the same stream 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); } } 

Then called with:

 DateTime.Now.StartOfWeek().ToString("Md-yyyy"); 
+1
source

Source: https://habr.com/ru/post/1346813/


All Articles