DateFormat parsing on MonoTouch - c#

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.

Related

Parsing Date Time string produces unexpected results

I'm trying to convert a string which is in the correct format into a date of exactly the same format for a linq query to work against a SQL date.
I've tried several conversion methods but all have failed. The example below shows the issue:
var test = DateTime.ParseExact("2019-04-09 13:15:00", "yyyy-MM-dd HH:mm:ss", null);
produces
{09/04/2019 13:15:00}
I have no idea why the date comes out like this but I would like to come out like:
2019-04-09 13:15:00
I tried with culture info but no luck. Not sure why this happening?
You have a fundamental misunderstanding of how DateTime values work. They do not have any human-readable format. Rather, they are stored as a binary value that is not human readable. The format you're seeing is something provided as a convenience by your debugger.
If you need a different specific format for anything other than use in SQL*, you can call ToString() with the appropriate format string. Just remember when you do that you are no longer working with a DateTime value, but are back to using a string again, and the best practice is to wait as long as possible before going back to strings.
*For SQL, you should be using parameterized queries, where there is a placeholder in the query and your datetime value is assigned directly to the parameter value without converting to a string first.
You parse the date in the correct format, so that's fine. The DateTime-object contains the correct value, so you can use it for your database.
If you want to see it in your prefered format you also need to output it using the same format, otherwise the default format of your user account (or in case of a web request the preferred language of the calling browser) will be used for displaying it.
Console.WriteLine(test.ToString("yyyy-MM-dd HH:mm:ss"));
If you are using Visual Studio, you can execute this command in the "Immediate Window" while running the debugger:
test.ToString("yyyy-MM-dd HH:mm:ss")
In other windows the debugger will use the default output format like described above.

Inconsistent Date Format when writing a CSV

I'm facing a very strange issue. I'm writing to a CSV file like this:
sw.WriteLine($"{posting.publishedOn},{posting.ExpirationDate}");
Posting Date is a DateTime object and Expiration Date is a DateTime? object.
However, when I run this on my production server in Germany, it's very inconsistent as to which date format it prints out. Sometimes I will have dates formatted like this (European style):
Posting Date,Expiration Date
06.08.2018 11:49,08.07.2018 11:49
And sometimes I will have dates formatted like this (U. S. style):
Posting Date,Expiration Date
8/15/2018 7:56:12 AM,10/14/2018 7:56:12 AM
Posting Date and Expiration Date are completely separate .NET Objects, but each line will be consistent - i.e. if one column is in European format, the other one will be as well.
I tried setting the culture like this:
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
but it didn't seem to make a difference.
This happens when I run the console application on my server in Germany.
What could be causing this? Is there a way to fix it without having to explicitly call ToString with a format every time I write a date?
Set the format explicitly, for example:
sw.WriteLine($"{posting.publishedOn.ToString("MM/dd/yyyy hh:mm tt")},{posting.ExpirationDate?.ToString("MM/dd/yyyy hh:mm tt")??""}");
EDIT: Just realized you explicitly said you don't want this solution. I'm going to leave my answer in case others find your question and ToString is a suitable solution.
Are you absolutely sure that the serialization is always happening in the same thread whose culture is being set?
Because if not, that may be the issue.
Just to debug it, please set the current thread culture immediately before the serialization code and check if the issue still happens, i.e.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
sw.WriteLine($"{posting.publishedOn},{posting.ExpirationDate}");
I believe you need to just set the specific culture like so:
CultureInfo.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

Format c# dateTime to local string format

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.

Change datetime to different culture

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.

C Sharp DateTime Format

UPDATE This looks to be a bug in Windows 7. I tested the same scenario with Windows 8 and I cannot replicate this there. Please see the MS Bug Report that I posted on this issue if you want more information. Thank you again to all that helped.
UPDATE 2 The error happens on Server 2008 R2 as well (Kind of expected that)
Original Submission
Using the examples on the following page Date Formats I am able to control the format of my date. However, one of my clients, using Windows 7, modified their calendar to display their short date like this 'ddd MM/dd/yy', see the image for the settings. .
This displays the clock like this .
This works fine except when I use a date on their machine. When I format the date like the following...
String.Format("{0:MM/dd/yy}", dt); //the result is 06 04 13, notice the spaces
If I take off the ddd to display the day of week in the calendar settings and use the same format option I see the following...
String.Format("{0:MM/dd/yy}", dt); //the result is 06/04/13, this time it has forward slashes
The .ToShortDateString() option on the date gives me "Tue 06/04/13" and crashes when going into a database. This is how the issue was found.
Outside of hard coding the format, i.e. joining the month to the forward slash to the day etc, does anyone know of what else I can try to get this to work?
It sounds like you are formatting the date as a string in order to send it in via some SQL. Have you considered using command parameters for this instead of string formatting?
Using the InvariantCulture should work. I created a test console app to check it. The code changes the thread's current culture to be the Invariant one:
class Program
{
static void Main(string[] args)
{
/// Displays '06 04 13'
Console.WriteLine(string.Format("{0:MM/dd/yy}", System.DateTime.Now));
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
/// Displays '06/04/13'
Console.WriteLine(string.Format("{0:MM/dd/yy}", System.DateTime.Now));
Console.ReadLine();
}
}
Edited To Note: This looks to be a bug with Windows 7. When changing the short date pattern via the control panel, using the "additional settings" tab as in the OP's post, both the CurrentCulture and CurrentUICulture's date separator gets changed as well.
When you modify the short date format, it looks like the first non-format character is picked up as the date separator for the current culture. Both CurrentCulture and CUrrentUiCulture are modified to reflect that [unintended] customization. Looks like some [bright] developer made the [unwarranted] assumption that nobody would ever have a short date format that included something like day of the week.
Nice catch! Are you going to report the bug to Microsoft?
If you use the invariant culture to format dates, etc., user settings won't affect you. Try something like
String.Format( CultureInfo.InvariantCulture , "{0:MM/dd/yy}", dt);
or use an instance of the culture you want:
CultureInfo usa = CultureInfo.GetCultureINfo("en-US") ;
string.Format( usa , "{0:MM/dd/yy}" , dt ) ;
However, if the culture you specified matches the current culture set for the Windows OS, user customizations are applied: meaning, you'll have the same problem unless you use a culture that isn't the current windows culture.
More details at MDSN:
CultureInfo
Standard DateTime Format Strings
Custom DateTime Format Strings
Without specifying a specific culture, you'll get the current user's CurrentCulture or CurrentUICulture with any user-specified mods applied to it.
For those interested in more information on this please go to the MS Forums post that I put HERE.

Categories