How to get DayOfWeek in a local CultureInfo? - c#

DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
string day = dt.DayOfWeek.ToString();
day = day.Substring(0, 1).ToUpper();
MessageBox.Show(day); // result is "F"
How could I get the result in a local language (CultureInfo), for example - France and where can I find a list of languages references for this purpose ?

Assuming you've already got the CultureInfo, you can use:
string dayName = dateTime.ToString("dddd", culture);
You'd then need to take the first character of it yourself - there's no custom date/time format for just that. You could use ddd for the abbreviated day name, but that's typically three characters, not one.
As for a list of cultures - you can use CultureInfo.GetCultures. It will vary by platform, and could vary over time and even by version of .NET, too.
As an aside, this code isn't ideal:
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
If you happen to call it just before midnight at the end of a year, you could get the "old" year but then January as the month. You should evaluate DateTime.Now (or DateTime.Today) once, and then use the same value twice:
DateTime today = DateTime.Today;
DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);

Straight from the MSDN: MSDN on DateTime with CultureInfo
DateTime dt = DateTime.Now;
// Sets the CurrentCulture property to U.S. English.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
// Displays dt, formatted using the ShortDatePattern
// and the CurrentThread.CurrentCulture.
Console.WriteLine(dt.ToString("d"));

Try dt.ToString("dddd") and then manipulate that string if necessary. See Custom Date and Time Format Strings.

DateTime dateValue = new DateTime(2008, 6, 11);
Console.WriteLine(dateValue.ToString("ddd",
new CultureInfo("fr-FR")));

it is as simple as this:
var culture = new CultureInfo("da-DK");
var datestring =datetime.ToString("dd MMMMM yyyy kl. hh:mm",culture)

Related

Iterating through a DateTime in MMM yyyy format

I have a couple of DateTime startTime and endTime. I would like them to be in MMM yyyy format ("August 2017") but if I parse them ToString, i can't loop because, well, it's a string now, there is no AddMonths method. For exemple :
var formattedStartTime = startTime.ToString("MMMM yyyy");
var formattedEndTime = endTime.ToString("MMMM yyyy");
for (var date = formattedStartTime; date < formattedEndTime; date = date.AddMonths(1)) // nope
How can i parse my variables and loop through every month in between two dates ?
By calling ToString you are obviously converting your dates to a string, which know nothing about the original date they represent and as such also cannot perform any date related operations.
The solution is to simply convert to string only when you are actually displaying the object:
for (var date = startTime; date < endTime; date = date.AddMonths(1))
{
Console.WriteLine(date.ToString("MMM yyyy"));
}
Be careful with such date comparisons though, since depending on the actual days of the month and the time component in the startTime and endTime, you might skip or include a result you do not expect.
For example with startTime = new DateTime(2017, 1, 2) and endTime = new DateTime(2017, 2, 3) (February 3rd), you would get February in the result but with endTime = new DateTime(2017, 2, 1) (February 1st) you wouldn’t.

C# DateTime.ParseExact determining year prefix

I have a requirement regarding the parsing of date strings of the form "dd/MM/yy" such that if the year is deemed greater than 30 years from the current year then it would prefix the year with 19. In the other instance it is prefixed with 20.
Examples:
01/01/50 -> 01/01/1950
01/01/41 -> 01/01/2041
I'm not sure how DateTime.ParseExact decides what prefix it should use or how I can force it one way or the other (it does appear to make a sane assumption as 01/01/12 -> 01/01/2012, I just don't know how to dictate the point at which it will switch).
Use the Calendar.TwoDigitYearMax property.
Gets or sets the last year of a 100-year range that can be represented
by a 2-digit year.
In your case, something like this would work:
// Setup
var cultureInfo = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
var calendar = cultureInfo.Calendar;
calendar.TwoDigitYearMax = DateTime.Now.Year + 30;
cultureInfo.DateTimeFormat.Calendar = calendar;
// Parse
var _1950 = DateTime.ParseExact("01/01/50", "dd/MM/yy", cultureInfo);
var _2041 = DateTime.ParseExact("01/01/41", "dd/MM/yy", cultureInfo);
I do not think that ParseExact can do your job, so here my version with conditional blocks but works.
Try This:
DateTime currentDate = DateTime.Now;
String strDate = "01/01/41";
DateTime userDate=DateTime.ParseExact(strDate, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
currentDate=currentDate.AddYears(30);
if ((userDate.Year%100) > (currentDate.Year%100))
{
strDate = strDate.Insert(6, "19");
}
else
{
strDate = strDate.Insert(6, "20");
}
DateTime newUserDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

How to get the previous month date in asp.net

I need to get the previous months date in asp.net which means that if the current date is 5/2/2013 then I want to display the previous date as 5/1/2013. How to solve this?
Try this :
DateTime d = DateTime.Now;
d = d.AddMonths(-1);
The solution is to substract 1 month:
DateTime.Now.AddMonths(-1)
Or if not just build the datetime object from scratch:
var previousDate = DateTime.Now.AddMonth(-1);
var date = new DateTime(previousDate.Year, previousDate.Month, DateTime.Now.Day);
this time you are guaranteed that the year and month are correct and the day stays the same. (although this is not a safe algorithm due to cases like the 30th of march and the previous date should be 28/29th of February, so better go with the first sugeestion of substracting a month)
If you already have date time in string format
var strDate = "5/1/2013";
var dateTime = DateTime.ParseExact(strDate,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
var lastMonthDateTime = dateTime.AddMonths(-1);
else if you have DateTime object just call it's AddMonths(-1) method.

C# Creating a DateTime Object That Represents the Taiwan Date Feb 29th 101 (Leap Day)

I'm having an impossible time creating a DateTime object that stores the date 02/29/101 (Taiwan Date) in C# without changing the Thread culture.
When I do this:
DateTime date = new DateTime(2012, 2, 29, new TaiwanCalendar());
It creates a DateTime object with a date 1911 years in the future. It seems this overload is meant to tell the DateTime object that you're providing a Taiwan date, not that you want a Taiwan date.
I can do this
DateTime leapDay = new DateTime(2012, 2, 29);
string date = string.Format("{0}/{1}/{2}", new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
but that's a string representation, and my calling code needs a DateTime object returned and this:
DateTime leapDay = new DateTime(2012, 2, 29);
DateTime date = new DateTime(new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
doesn't work (I get an error saying "Year, Month, and Day parameters describe an un-representable DateTime.").
I need a DateTime object that can accurately represent a Taiwan date without changing the thread culture. This works:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-TW");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar = new TaiwanCalendar();
DateTime date = new DateTime(2012, 2, 29);
but as soon as I change the thread culture back to en-US the date changes back automatically which prevents me from returning it as a Taiwan date.
Is there any way to do this, or am I going to have to pass my date around as a string?
DateTime values are always in the Gregorian calendar, basically. (Either that, or you can think of them as always being "neutral", but the properties interpret the value as if it's in the Gregorian calendar.) There's no such thing as "A DateTime in a Taiwan calendar" - you use the TaiwanCalendar to interpret a DateTime in a particular way.
If you need to format the DateTime using a particular calendar, you can create the appropriate CultureInfo and pass that to the ToString method. For example:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var calendar = new TaiwanCalendar();
var date = new DateTime(101, 2, 29, calendar);
var culture = CultureInfo.CreateSpecificCulture("zh-TW");
culture.DateTimeFormat.Calendar = calendar;
Console.WriteLine(date.Year); // 2012
Console.WriteLine(date.ToString(culture)); // 101/2/29 [etc]
Console.WriteLine(date.ToString("d", culture)); // 101/2/29
}
}
EDIT: As noted by xanatos, you might also want to consider Calendar.ToDateTime. (I'd love to say think about using Noda Time instead, but we don't support this calendar yet. When we do...)
var timeToConvert = DateTime.Now; //whereever you're getting the time from
var est = TimeZoneInfo.FindSystemTimeZoneById("Taipei Standard Time");
return TimeZoneInfo.ConvertTime(timeToConvert, est).ToString("MM-dd-yyyy");

Parsing a Date Range in C# - ASP.NET

Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?
I know I could use:
DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));
Is there a better way?
var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
var endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);
Instead of Convert.ToDateTime, it could be worth to use DateTime.Parse and explicitely put in the Culture you desire. If I try that example with any European Culture, i get an Error because 11/13/2008 points to the 11th Day in the 13th Month of 2008...
CultureInfo ci = new CultureInfo("en-us");
var startDate = DateTime.Parse(components[0], ci);

Categories