I have a DateTime C# object (in a Unity script, targeted for an Android device). I want to retrieve a string representation via .toString() (so w/o any special formatting parameter), which is supposed to deliver a short form like "10/5/2014 9.17 PM". If I now run it on an Android device with the locale set to e.g. German, just the time will be converted correctly, while the date stays in US format (so "10/5/2014 21.17" instead of "5.10.2014 21.17").
Am I doing something wrong here, or maybe don't I understand the whole thing at all ;-)
Your assumption about DateTime.ToString is correct. The following code prints 05.10.2014 13:26:36:
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
DateTime time = DateTime.Now;
Console.WriteLine(time.ToString());
I'd check what the value of Thread.CurrentThread.CurrentCulture.ToString() is in your environment and ensure that Unity sets it correctly. If it doesn't, you would have to do it yourself.
Related
I'm relatively new to C# and I'm still learning a lot. I also searched stackoverflow for similar problems but got to a point where I'm stuck.
In my VSTO Excel project I'd like to output dynamic data coming from a database with a predefined number format per column also coming from the database. The user can define his own layout of the report. Everything is working just fine, I have just problems formatting the date value.
When it's about to output a date column, the format should be automatically be determined by the program instead of predefining it in the database as well. The date value gets already inserted in the Excel sheet as the decimal number it should be. Everything okay here. When I manually format it in Excel itself, it is displayed correctly.
But I want to format the date with C# like it would be formatted when I do it manually by clicking on the short date format in Excel. And it should work in every country, regardless in which language the office package was installed.
I'm working with a German installation and I expect the format to be "TT.MM.JJJJ". When formatting the column with this fixed string, it works perfectly (at least in Germany I guess).
It makes no difference if formatting it with
CurrentWorksheet.Columns[queryColumn.Position].NumberFormat = "TT.MM.JJJJ";
or
CurrentWorksheet.Columns[queryColumn.Position].NumberFormatLocal = "TT.MM.JJJJ";
Both end up in the same (correct) result. That the first line is working as well is the first thing which was unexpected for me, but that's not the main point. I tried to format it dynamically by replacing "TT.MM.JJJJ" with the following lines:
// Leads to dd.MM.yyyy
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
// Fixed German culture still leads to dd.MM.yyyy
CultureInfo.CreateSpecificCulture("de-DE").DateTimeFormat.ShortDatePattern;
// MM/dd/yyyy - also not helpful
CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern;
When using the first or second ShortDatePattern the date 27.08.2014 is shown as "dd.08.yyyy". Excel simply doesn't unterstand "dd" or "yyyy". I thought at least when using NumberFormat instead of NumberFormatLocal it would work, because it's the global format, but it doesn't. It feels like Microsoft has implemented the date formatting more complicated that it could be.
How would I determine the correct date pattern here?
The answer (it still is a kind of workaround) is pretty much found in another question:
How to set localized short-date format for a cell in Excel with C#?
There's just a very small difference I had to make in the method for constructing the ShortDatePattern (the Application parameter for DateFormatComponentCodes).
public static string ConstructExcelShortDatePattern()
{
var systemDateComponentCodes = new DateFormatComponentCodes();
var excelDateComponentCodes = new DateFormatComponentCodes(Globals.ThisAddIn.Application);
string systemShortDatePattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
string excelShortDatePattern = systemShortDatePattern.Replace(systemDateComponentCodes.Year, excelDateComponentCodes.Year).Replace(systemDateComponentCodes.Month, excelDateComponentCodes.Month).Replace(systemDateComponentCodes.Day, excelDateComponentCodes.Day);
return excelShortDatePattern;
}
Thanks to Heinzi for finding a great answer and Jordan for providing such a useful class!
I have the following code:
DateTime.TryParse("06-28-2012", new System.Globalization.CultureInfo("en-NZ"),
System.Globalization.DateTimeStyles.AssumeLocal, out date);
I'm not sure why this is returning true since if I go into my Regional Settings in Windows, I only see the following date formats under short date:
d/MM/yyyy
d/MM/yy
dd/MM/yy
d.MM.yy
yyyy-MM-dd
So then why is a short date format like MM-dd-yyyy returning true? Shouldn't it return false?
I'm using this similar post as a source: DateTime c# parsing
Important:
Please note that I also have my regional settings set to use English (New Zealand) and chose
yyyy-MM-dd as my short date format.
Having your short date format set to yyyy-MM-dd is the cause of this behavior (I do not know if that the standard in New Zealand, but New Zealand's short date is set to d/MM/yyyy on my computer). I do not know if Dot Net, or the underlying Windows APIs are to blame, but it seems like it's smart enough to understand that the 4-digits part represents the year, and after that it just preserves the month-day order (Note that calling DateTime.TryParse("28-06-2012") will actually fail).
You can try using ParseExact, but be warned that will fail on a slightest change of the string (for example, when using a dot or a slash as a separator, instead of a dash.
In my opinion, it's probably best to leave the behavior as is, as it can handle more cases, but if you really must check if a date string was in a specified (yet flexible) format, Regex is the best option. For example Regex.IsMatch("2012/06/28", #"[0-9][0-9][0-9][0-9][./\\][0-9][0-9]?[./\\][0-9][0-9]?"); should suit your needs, while still allowing some flexibility.
You could try DateTime.ParseExact
Could you execute and post the result from the code below?
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.DateSeparator;
I have a datetime in this format "Wednesday, December 04, 2013". I want to translate it to different cultures at runtime so that i am able to store that in database according to culture.
This is my code:
dysMngmt.Day = curntDate.ToString("D");
The one line code above is getting the day.
So,please help me.
You can use the second argument of the ToString function, which enables you to pick a culture you see fit:
curntDate.ToString("D", CultureInfo.GetCultureInfo("en-US"))
As a side note, why are you saving the date in your database as a string? Why not use a native date date type? It will take less space and allow you comparisons etc., and then you'd just use the currect culture when reading it out of the database.
Unless you have a very good reason for handling the culture of each date seperatly within the application you should set this at the application level so that the default ToString() works with your intended culture.
http://support.microsoft.com/kb/306162
Also, you should probably also not store dates as text in your database.
I have an sql query that saves a list of Dates (public holidays) to the database. This works fine on Windows and Android, but it fails on MonoTouch. It fails in the line below.
DateTime.Parse("01/01/2013").Date
It seems that MonoTouch is not able to parse this date. I know how to fix it by creating the DateTime object directly, but I just want to know if there is something that I am missing or is it a bug in MonoTouch?
I fixed it by instantiating the DateTime object directly like this:
new DateTime(2013,01,01)
This is happening because you have your culture set to something that does not recognize "01/01/2013" as a default date format. Your code works for me, but I am using "en-us" culture where MM/DD/YYYY is the standard format.
You can use Date.ParseExact() and specify a date format to override whatever the default for your culture is.
I want to convert a date in c# like 2012-06-28T14:30:00-04:00 in to "yyyyMMddTHHmm" format both dates are in string.
string currentDate="2012-06-28T14:30:00-04:00";
string requiredDate="yyyyMMddTHHmm"
When i am trying to convert this date with Convert.ToDateTime() then C# return "20120629T0000-04:00" but this is not correct date.
Have a look at the Standard Date and Time Format Strings (MSDN). I guess it might be enough to use just the ToString() method on your DateTime instances.
Possibly you might need to specify CultureInfo (MSDN here) in the appropriate overloads of the convert methods. Possibly the server and client applications are in different cultures and/or timezones.
DateTime.Parse("2012-06-28T14:30:00-04:00").ToString("yyyyMMddTHHmm") produces value you may want.
Note that changing value from absolute ISO8601 format to local ISO8601 format should be done carefully as it changes meaning of the value and often value itself.
Please make sure which of the following options you really want (and adjust code accordingly):
simply drop time from the value. Will produce semi-random time if values are coming from different time-zones.
always move value to a given timezone and make it local to that timezone.
always move value to current timezone and make it local to current timezone
Or maybe you are looking for something else altogether.
I'm not sure this is the format you are trying out
string currentDate="2012-06-28T14:30:00-04:00";
DateTime.Parse(currentDate).ToString("o")
This will give you 2012-06-29T00:00:00.0000000+05:30