How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
DateTime.Now.StartWeek(Monday);
Use an extension method:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
Which can be used as follows:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
The quickest way I can come up with is:
var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
If you would like any other day of the week to be your start date, all you need to do is add the DayOfWeek value to the end
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
A little more verbose and culture-aware:
System.Globalization.CultureInfo ci =
System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;
Using Fluent DateTime:
var monday = DateTime.Now.Previous(DayOfWeek.Monday);
var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);
Ugly but it at least gives the right dates back
With start of week set by system:
public static DateTime FirstDateInWeek(this DateTime dt)
{
while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
dt = dt.AddDays(-1);
return dt;
}
Without:
public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)
{
while (dt.DayOfWeek != weekStartDay)
dt = dt.AddDays(-1);
return dt;
}
Let's combine the culture-safe answer and the extension method answer:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));
}
}
This would give you the preceding Sunday (I think):
DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);
For Monday
DateTime startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);
For Sunday
DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);
This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week.
It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:-
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
DateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);
The code for the previous Sunday is simpler as we don't have to make this adjustment:-
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);
using System;
using System.Globalization;
namespace MySpace
{
public static class DateTimeExtention
{
// ToDo: Need to provide culturaly neutral versions.
public static DateTime GetStartOfWeek(this DateTime dt)
{
DateTime ndt = dt.Subtract(TimeSpan.FromDays((int)dt.DayOfWeek));
return new DateTime(ndt.Year, ndt.Month, ndt.Day, 0, 0, 0, 0);
}
public static DateTime GetEndOfWeek(this DateTime dt)
{
DateTime ndt = dt.GetStartOfWeek().AddDays(6);
return new DateTime(ndt.Year, ndt.Month, ndt.Day, 23, 59, 59, 999);
}
public static DateTime GetStartOfWeek(this DateTime dt, int year, int week)
{
DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
return dayInWeek.GetStartOfWeek();
}
public static DateTime GetEndOfWeek(this DateTime dt, int year, int week)
{
DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
return dayInWeek.GetEndOfWeek();
}
}
}
Putting it all together, with Globalization and allowing for specifying the first day of the week as part of the call we have
public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )
{
DayOfWeek fdow;
if ( firstDayOfWeek.HasValue )
{
fdow = firstDayOfWeek.Value;
}
else
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
fdow = ci.DateTimeFormat.FirstDayOfWeek;
}
int diff = dt.DayOfWeek - fdow;
if ( diff < 0 )
{
diff += 7;
}
return dt.AddDays( -1 * diff ).Date;
}
Step 1:
Create a static class
public static class TIMEE
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 - (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(1 * diff).Date;
}
}
Step 2: Use this class to get both start and end day of the week
DateTime dt = TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);
var now = System.DateTime.Now;
var result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
This would give you midnight on the first Sunday of the week:
DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, t.Hour, t.Minute, t.Second);
This gives you the first Monday at midnight:
DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek - 1, t.Hour, t.Minute, t.Second);
Try with this in C#. With this code you can get both the first date and last date of a given week. Here Sunday is the first day and Saturday is the last day, but you can set both days according to your culture.
DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Sunday);
DateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);
public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
DateTime firstDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
return firstDayInWeek;
}
public static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)
{
DateTime lastDayInWeek = dayInWeek.Date;
while (lastDayInWeek.DayOfWeek != firstDay)
lastDayInWeek = lastDayInWeek.AddDays(1);
return lastDayInWeek;
}
I tried several, but I did not solve the issue with a week starting on a Monday, resulting in giving me the coming Monday on a Sunday. So I modified it a bit and got it working with this code:
int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
return monday;
The same for end of the week (in style of Compile This's answer):
public static DateTime EndOfWeek(this DateTime dt)
{
int diff = 7 - (int)dt.DayOfWeek;
diff = diff == 7 ? 0 : diff;
DateTime eow = dt.AddDays(diff).Date;
return new DateTime(eow.Year, eow.Month, eow.Day, 23, 59, 59, 999) { };
}
Thanks for the examples. I needed to always use the "CurrentCulture" first day of the week and for an array I needed to know the exact Daynumber.. so here are my first extensions:
public static class DateTimeExtensions
{
//http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
//http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1
public static DateTime StartOfWeek(this DateTime dt)
{
//difference in days
int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.
//As a result we need to have day 0,1,2,3,4,5,6
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
public static int DayNoOfWeek(this DateTime dt)
{
//difference in days
int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.
//As a result we need to have day 0,1,2,3,4,5,6
if (diff < 0)
{
diff += 7;
}
return diff + 1; //Make it 1..7
}
}
Here is a correct solution. The following code works regardless if the first day of the week is a Monday or a Sunday or something else.
public static class DateTimeExtension
{
public static DateTime GetFirstDayOfThisWeek(this DateTime d)
{
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
var first = (int)ci.DateTimeFormat.FirstDayOfWeek;
var current = (int)d.DayOfWeek;
var result = first <= current ?
d.AddDays(-1 * (current - first)) :
d.AddDays(first - current - 7);
return result;
}
}
class Program
{
static void Main()
{
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine("Current culture set to en-US");
RunTests();
Console.WriteLine();
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("da-DK");
Console.WriteLine("Current culture set to da-DK");
RunTests();
Console.ReadLine();
}
static void RunTests()
{
Console.WriteLine("Today {1}: {0}", DateTime.Today.Date.GetFirstDayOfThisWeek(), DateTime.Today.Date.ToString("yyyy-MM-dd"));
Console.WriteLine("Saturday 2013-03-02: {0}", new DateTime(2013, 3, 2).GetFirstDayOfThisWeek());
Console.WriteLine("Sunday 2013-03-03: {0}", new DateTime(2013, 3, 3).GetFirstDayOfThisWeek());
Console.WriteLine("Monday 2013-03-04: {0}", new DateTime(2013, 3, 4).GetFirstDayOfThisWeek());
}
}
Modulo in C# works bad for -1 mod 7 (it should be 6, but C# returns -1)
so... a "one-liner" solution to this will look like this :)
private static DateTime GetFirstDayOfWeek(DateTime date)
{
return date.AddDays(
-(((int)date.DayOfWeek - 1) -
(int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
}
I did it for Monday, but with similar logic for Sunday.
public static DateTime GetStartOfWeekDate()
{
// Get today's date
DateTime today = DateTime.Today;
// Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc
var todayDayOfWeek = (int)today.DayOfWeek;
var dateStartOfWeek = today;
// If today is not Monday, then get the date for Monday
if (todayDayOfWeek != 1)
{
// How many days to get back to Monday from today
var daysToStartOfWeek = (todayDayOfWeek - 1);
// Subtract from today's date the number of days to get to Monday
dateStartOfWeek = today.AddDays(-daysToStartOfWeek);
}
return dateStartOfWeek;
}
The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:
private DateTime getStartOfWeek(bool useSunday)
{
DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
if(!useSunday)
dayOfWeek--;
if(dayOfWeek < 0)
{// day of week is Sunday and we want to use Monday as the start of the week
// Sunday is now the seventh day of the week
dayOfWeek = 6;
}
return now.AddDays(-1 * (double)dayOfWeek);
}
You could use the excellent Umbrella library:
using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();
However, they do seem to have stored Monday as the first day of the week (see the property nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn), so that previous localized solution is a bit better. Unfortunate.
Edit: looking closer at the question, it looks like Umbrella might actually work for that too:
// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday();
DateTime sunday = DateTime.Now.PreviousSunday();
Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use BeginningOfWeek, which seems like a bug :(.
Following on from Compile This' answer, use the following method to obtain the date for any day of the week:
public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)
{
var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);
var diff = dayOfWeek - DayOfWeek.Monday;
if (diff == -1)
{
diff = 6;
}
return monday.AddDays(diff);
}
This will return both the beginning of the week and the end of the week dates:
private string[] GetWeekRange(DateTime dateToCheck)
{
string[] result = new string[2];
TimeSpan duration = new TimeSpan(0, 0, 0, 0); //One day
DateTime dateRangeBegin = dateToCheck;
DateTime dateRangeEnd = DateTime.Today.Add(duration);
dateRangeBegin = dateToCheck.AddDays(-(int)dateToCheck.DayOfWeek);
dateRangeEnd = dateToCheck.AddDays(6 - (int)dateToCheck.DayOfWeek);
result[0] = dateRangeBegin.Date.ToString();
result[1] = dateRangeEnd.Date.ToString();
return result;
}
I have posted the complete code for calculating the begin/end of week, month, quarter and year on my blog
ZamirsBlog
Calculating this way lets you choose which day of the week indicates the start of a new week (in the example I chose Monday).
Note that doing this calculation for a day that is a Monday will give the current Monday and not the previous one.
//Replace with whatever input date you want
DateTime inputDate = DateTime.Now;
//For this example, weeks start on Monday
int startOfWeek = (int)DayOfWeek.Monday;
//Calculate the number of days it has been since the start of the week
int daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;
DateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);
I work with a lot of schools, so correctly using Monday as the first day of the week is important here.
A lot of the most terse answers here don't work on Sunday -- we often end up returning the date of tomorrow on Sunday, which is not good for running a report on last week's activities.
Here's my solution, which returns last Monday on Sunday, and today on Monday.
// Adding 7 so remainder is always positive; Otherwise % returns -1 on Sunday.
var daysToSubtract = (7 + (int)today.DayOfWeek - (int)DayOfWeek.Monday) % 7;
var monday = today
.AddDays(-daysToSubtract)
.Date;
Remember to use a method parameter for "today" so it's unit testable!!
Here is a combination of a few of the answers. It uses an extension method that allows the culture to be passed in. If one is not passed in, the current culture is used. This will give it maximum flexibility and reuse.
/// <summary>
/// Gets the date of the first day of the week for the date.
/// </summary>
/// <param name="date">The date to be used</param>
/// <param name="cultureInfo">If none is provided, the current culture is used</param>
/// <returns>The date of the beggining of the week based on the culture specifed</returns>
public static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>
date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo ?? CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;
Example Usage:
public static void TestFirstDayOfWeekExtension() {
DateTime date = DateTime.Now;
foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {
Console.WriteLine($"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}");
}
}
If you want Saturday or Sunday or any day of week, but not exceeding the current week (Sat-Sun), I got you covered with this piece of code.
public static DateTime GetDateInCurrentWeek(this DateTime date, DayOfWeek day)
{
var temp = date;
var limit = (int)date.DayOfWeek;
var returnDate = DateTime.MinValue;
if (date.DayOfWeek == day)
return date;
for (int i = limit; i < 6; i++)
{
temp = temp.AddDays(1);
if (day == temp.DayOfWeek)
{
returnDate = temp;
break;
}
}
if (returnDate == DateTime.MinValue)
{
for (int i = limit; i > -1; i++)
{
date = date.AddDays(-1);
if (day == date.DayOfWeek)
{
returnDate = date;
break;
}
}
}
return returnDate;
}
We like one-liners: Get the difference between the current culture's first day of week and the current day, and then subtract the number of days from the current day:
var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));
I'm writing a C# console application where you enter your name and birthdate in yyyy/mm/dd format to have the console tell you your age in years and months. Now I've got that part figured out and it works. Until I tried to also implement a try and catch exception to check if the date you entered was in the right format. If not it should tell you to try again 3 times before telling you the date format is incorrect and then quitting the app.
Now the problem is the app works sort of, but it tells you the date format is incorrect even when it isn't. Then still continues to give the correct output after looping through the app that asks for name and date of birth 3 times. This is the code I have so far(I know the year month output is a bit messy I just spent way too long testing too much stuff to try and change it now, I am open to improvements and changes though):
namespace CSConsoleDateTimeTypes
{
class Program
{
static int Count = 0;
static void Main(string[] args)
{ EnterDate(); }
static void EnterDate()
{
string userName, enteredDoBString;
Console.WriteLine("Enter your name:");
userName = Console.ReadLine();
Console.WriteLine("Enter your date of birth in the format yyyy/mm/dd:");
enteredDoBString = Console.ReadLine();
string dateString = Console.ReadLine();
parseDateString(dateString);
DateTime enteredDoB = DateTime.Parse(enteredDoBString);
Console.WriteLine("Your DoB is: {0}", enteredDoB);
DateTime dateToday = DateTime.Today;
if (dateToday < enteredDoB)
{
DateTime date4 = dateToday;
dateToday = enteredDoB;
enteredDoB = date4;
}
TimeSpan ts = dateToday - enteredDoB;
//total days (irrelevant to the application though)
Console.WriteLine(ts.TotalDays);
//total years
int years = dateToday.Year - enteredDoB.Year;
int months = 0;
//Total months
if (dateToday.Month < enteredDoB.Month)
{
months = 12 - dateToday.Month + enteredDoB.Month;
}
else
{
months = enteredDoB.Month - dateToday.Month;
}
if (months > 12)
{
Console.WriteLine("Years: {0}, Months: {1}", years - 1, 12 - (months - 12));
}
else if (months < 0)
{
Console.WriteLine("Years: {0}, Months: {1}", years, months - months);
}
else
{
Console.WriteLine("Years: {0}, Months: {1}", years, months);
}
Console.ReadKey();
Console.ReadKey();
}
static void parseDateString(string datestring)
{
try
{
DateTime date3 = DateTime.Parse(datestring, System.Globalization.CultureInfo.InvariantCulture);
date3.ToShortDateString();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//if date was entered incorrectly 3 times, the application should exit..
Count++;
if (Count < 3)
{
EnterDate();
}
else
{
Console.WriteLine("\aSorry date still not in correct format - Press any key to exit the application");
Console.ReadKey();
}
}
}
}
}
This is the output it gives when I launch the app and it finishes running through all the code after my inputs:
Enter your name:
gerrit
Enter your date of birth in the format yyyy/mm/dd:
1997/02/13
String was not recognized as a valid DateTime.
Enter your name:
gerrit
Enter your date of birth in the format yyyy/mm/dd:
1997/02/13
String was not recognized as a valid DateTime.
Enter your name:
gerrit
Enter your date of birth in the format yyyy/mm/dd:
1997/02/13
String was not recognized as a valid DateTime.
Sorry date still not in correct format - Press any key to exit the application
Your DoB is: 1997/02/13 12:00:00 AM
7294
Years: 20, Months: 0
Your DoB is: 1997/02/13 12:00:00 AM
7294
Years: 20, Months: 0
Your DoB is: 1997/02/13 12:00:00 AM
7294
Years: 20, Months: 0
As you can see it asks for name and date of birth 3 times and still telling me date format is incorrect then it gives the correct output (Your DoB is: 1997/02/13 12:00:00 AM
7294
Years: 20, Months: 0) 3 times
It should ask once and output once but I can't figure out how to do it. Any help would be highly appreciated.
Here is a screenshot of the console output if it helps at all
http://i.imgur.com/qUpF0g2.png
I changed a little your code.
I don't have checked the rest of your code, only to ask the date.
private static void Main(string[] args)
{
EnterDate();
}
private static void EnterDate()
{
Console.WriteLine("Enter your name:");
var userName = Console.ReadLine();
// ask for date
var enteredDoBString = AskForDate();
if (enteredDoBString == null)
return;
DateTime enteredDoB = DateTime.Parse(enteredDoBString);
Console.WriteLine($"Your DoB is: {enteredDoB}");
DateTime dateToday = DateTime.Today;
if (dateToday < enteredDoB)
{
DateTime date4 = dateToday;
dateToday = enteredDoB;
enteredDoB = date4;
}
TimeSpan ts = dateToday - enteredDoB;
// total days (irrelevant to the application though)
Console.WriteLine(ts.TotalDays);
// total years
var years = dateToday.Year - enteredDoB.Year;
var months = 0;
// Total months
if (dateToday.Month < enteredDoB.Month)
{
months = 12 - dateToday.Month + enteredDoB.Month;
}
else
{
months = enteredDoB.Month - dateToday.Month;
}
if (months > 12)
{
Console.WriteLine($"Years: {years - 1}, Months: {12 - (months - 12)}");
}
else if (months < 0)
{
Console.WriteLine($"Years: {years}, Months: {months - months}");
}
else
{
Console.WriteLine($"Years: {years}, Months: {months}");
}
Console.ReadKey();
Console.ReadKey();
}
private static string AskForDate()
{
var count = 0;
while (count++ < 3)
{
try
{
Console.WriteLine("Enter your date of birth in the format yyyy/mm/dd:");
return DateTime.Parse(Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//if date was entered incorrectly 3 times, the application should exit..
}
}
Console.WriteLine("\aSorry date still not in correct format - Press any key to exit the application");
Console.ReadKey();
return null;
}
What I made:
I removed your function parseDateString and create a new called AskForDate. This function, like the name says, ask for the date to the user, and inside this function, the date entered is checked if is valid or not.
I believe that is better to check and ask on same function.
If the date entered by user is correct, the date is returned as ToShortDateString. If the date is incorrectly, the function ask two more times, and on third time, a null is returned.
Then, in the EnterDate function, if null is returned from AskForDate function, the program exits.
I also changed some strings interpolations, and removed some variables.
Ok, so I have a date stored in UK format (dd/mm/yy) which I need to display in the locale of wherever the user might be.
The issue is that this date can be 000000 (00/00/2000); so I can't convert it to DateTime directly, as DateTime doesn't support 0 values for day or month.
I have this so far:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
What's the correct way to add support for 0 values initially? I've tried changing the 0 to 1 before converting to DateTime, running the conversion and then replacing with a 0 again; but due to culture variants I see no way that this method can support other cultures, which is the purpose of this conversion to begin with.
Any ideas? I'm guessing this is a common issue.
Is this what you need ?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
I would not store dates like this as the methodology for doing so is already provided by the .NET framework.
The best way to store dates would be to use Culture.InvariantCulture for string conversion cases and then convert to local culture for display purposes as necessary. DateTime itself is culture-independent so converting between cultures is very easy.
I have this : Datetime.Now(); or 23/10/2009
I want this : Friday
For local date-time (GMT-5) and using Gregorian calendar.
//default locale
System.DateTime.Now.DayOfWeek.ToString();
//localized version
System.DateTime.Now.ToString("dddd");
To make the answer more complete:
DayOfWeek MSDN article
If localization is important, you should use the "dddd" string format as Fredrik pointed out - MSDN "dddd" format article
If you want to know the day of the week for your code to do something with it, DateTime.Now.DayOfWeek will do the job.
If you want to display the day of week to the user, DateTime.Now.ToString("dddd") will give you the localized day name, according to the current culture (MSDN info on the "dddd" format string).
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)
or
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)
DateTime.Now.DayOfWeek quite easy to guess actually.
for any given date:
DateTime dt = //....
DayOfWeek dow = dt.DayOfWeek; //enum
string str = dow.ToString(); //string
Here is more simple
DateTime dt;
string yourdate = dt.DayOfWeek.ToString()
better than declare redundant DayOfWeek
DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();
try this:
DateTime.Now.DayOfWeek
You're looking for the DayOfWeek property.
Here's the msdn article.
What about if we use String.Format here
DateTime today = DateTime.Today;
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
(DateTime.Parse((Eval("date").ToString()))).DayOfWeek.ToString()
at the place of Eval("date"),you can use any date...get name of day
I use this Extension Method:
public static string GetDayName(this DateTime date)
{
string _ret = string.Empty; //Only for .NET Framework 4++
var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
_ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name
_ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
return _ret;
}
Random Rnd = new Random();
RandomDates Rdate = new RandomDates();
PaymentDetails Payd = new PaymentDetails();
DayOfWeek strDay = DateTime.Today.DayOfWeek;
var dateTime = DateTime.Now;
var dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
StepDescription = "Fill MatterInformation. ";
Console.Write(" Input the Day : ");
dt = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Month : ");
mn = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Year : ");
yr = Convert.ToInt32(Console.ReadLine());
DateTime d = new DateTime(2021, 04, yr);
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var diff = d.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
diff += 7;
var x = d.AddDays(-diff).Date;
dateTime = DateTime.Now;
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
Console.WriteLine($"Date Value: {dateValue2}");
// strDay =
}
if (!strDay.Equals("Sunday") | !strDay.Equals("Saturday"))
{
Console.WriteLine("___________________OK____________________________________________");
// string NotificateionDate = Rdate.DateWithin_PastDays(Rnd.Next(30, 260)).ToString(#"MM\/dd\/yyyy");
// CustomLibrary.seWaitUntilElementIsVisible(10, NotiFiedDateTab.Actions.seGetLocator(), "NotiFiedDateTab");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else
{
Console.WriteLine("_________________________NOT______________________________________");
if (strDay.Equals("Sunday"))
{
dateTime = dateTime.AddDays(-2);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else if (strDay.Equals("Saturday"))
{
dateTime = dateTime.AddDays(-1);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the Day Number ");
int day = int.Parse(Console.ReadLine());
Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}
}
}