DateTime Conversion with Different Cultures - c#

I am wondering what is the best way to figure out how to convert a datetime?
Right now my computer is setup as dd/mm/yyyy yet I am taking date as mm/dd/yyy so when I try to do
DateTime.Convert();
DateTime.Parse();
DateTime.TryParse();
I either get nothing back or it crashes. Now I could tell it about the mm/dd/yyyy format and it probably would convert. However the problem is these dates are are coming from user uploaded files.
They could be in any format combination. I am trying to find ways to do it.
The problem I see is that I am looking at the dates in an uploaded file so I am not sure if looking say at the browser date format would help or not.
I am using asp.net mvc and I am trying to get a solution that handle date formats automatically so I don't have to ask the user about the date format they have (I figure the more things I have to ask them the less likely the user will continue on)

No, you can't figure out automatically what date-time format a user meant to use once the value is on the server. You need more information to parse it correctly (e.g. 1/2/3 can mean a lot of different dates depending on the culture).
Consider one of the following solutions:
Convert the entered date to a text representation in a standard format (i.e. ISO 8601 - 2012-02-09) using JavaScript on the client before you send it to the server. The code would look something like this: d.getUTCFullYear()+"-" + d.getUTCMonth() + "-" + d.getUTCDate().
Send the local culture information to the server along with date value to be converted and do the conversion on the server.
Force the user to enter the date in a specific format (e.g. Use 3 text boxes labeled "Month", "Day", and "Year" instead of one text box with free input).

chobo2 (I like the 'handle') :)
you can detect the locale culture and work on that at will. see the following SO Q/A for pointers:
Where is the system locale/culture set for .Net
the key is to NOT have to set anything in particular, but identify the locale and act accordingly.

Related

convert String to different datetime formats

My input is an annoying free text in which I need to extract the date. This date could be present in any of the formats with anomalies.
eg. This is 9.9.12 date
This is 9912 date
This is 0992012 date
Any possible format.
dMy
ddMMyy
ddMMyyyy
Mdyy etc..
I am able to validate if the text is in date format for ddMMy* but not any other. I was looking into this https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1 link to see what other formats could be possible but I got no leads.
Is this correct to write like in the following method for a date format say - 9912?
Date.ParseExact(test.ToString,"dMy", Globalization.CultureInfo.InvariantCulture)
If yes, the system is populating me the following err:
System.FormatException: String was not recognized as a valid DateTime.
Can anyone please share a reliable approach to tackle such problems?
There is no single way to accomplish what you're trying to do. Specifically, because the intent is so broad, it becomes hard to infer what the user actually means (e.g. how do you differentiate month vs. day).
Depending on how you're implementing your application, you need to implement input validation.
For a console app, I can envision you using something like:
if (DateTime.TryParse(line, out value))
{
// Parse-able date.
}
else
{
// Non-parseable date.
}
If you're building a WPF application, you can use binding validation. If you're building an ASP.NET MVC application, you can also implement model validation. Your mileage may vary - you should definitely consider constraining what your users can feed the application.

Why date is displayed differently at server and locally?

I am reading data from an API file, which has this format
<DataPoint>
<Amount>38.361</Amount>
<Time>2014-01-02T12:00:00</Time>
</DataPoint>
when I get the time, and print it at my website at visual studio I get 02/01/2014.
However, If I upload it, I get 1/2/2014.
Why the same code produces different results when I use it at my pc, and when I upload it at the server?
And how I can fix that?
ps: I am programming in C# and I am using the object JArray to get the data if this is important
JArray a = JArray.Parse(text);
But it
That's because of the DateTime CULTURE info. British dates are arranged as dd/MM/yyyy and American dates are MM/dd/yyyy You could just use Datetime.ToString("dd/MM/yyyy") to convert it to datetime format you want to display.
Format in which numeric and datetime values are transformed into string depends on OS culture settings, when you don't set them explicitly in code. Looks like that's the case here.
If you need the same date/numeric format everywhere, no matter how user set's the OS preferences, you should provide IFormatProvider instance which will provide the formatting and override OS default one.
The most commonly used is CultureInfo.InvariantCulture:
var dateString = myDate.ToString(CultureInfo.InvariantCulture);

get the format of a string date in c#

I have a string date like 'Wednesday, May 15, 2013' when I Parse it o lost the original format, is there a way to know what was the original format date or get it before the final Parse?
No, you'll lose the original format, if will now be a different object type with no care for its original format prior to parsing.
Your best option would be to store the pre-parse format prior to parsing as a different variable.
However if you simply wish to format the date in that original format, see Farhad's answer.
You can use this for getting date in a fromat you wish.
String.Format("{0:D}", DateTime.Now); // Tuseday, May 21, 2013
The DateTime struct does not have a format, it stores all of those values on various properties. When you want to display it you specify which format to use.
Using a format specifier when displaying it will likely do what you want. This mdsn article provides some basic information on format specifiers. The only way you can use the exact format you show there is if you know it ahead of time and have a format specifier for it. If you know you'll want to display strings in that format throughout the program it will be easy, if you get many different formats and want to decide how to display your dt at runtime it will be fairly complicated. I'm sure you could write some code to figure out what it is, but once the DateTime is created it will have no notion of what format the string used to create it was in.

Datetime formats and JSON data in C#

I'm having an issue with date/time formats in ASP.NET/C#. I have my SQL Server database set up with a PostDate field set to a type of "datetime". But it's saving the date in a strange format. I added a new row through a form and I got this as the date/time string:
2012-09-28 14:56:48.910
When it gets parsed by JSON.NET it gets even stranger. I get:
2012-09-28T14:56:48.91
The date and time are obviously correct, but how do I set things so that I can parse the date into a human-friendly way? There isn't really any code to post because the date is being added when the row is inserted. I'd like to format this as "Sept. 28, 2012 2:56 pm". How do I do that? Do I need to format the string before or after it's parsed as JSON?
That's not a "strange" format at all. The second form is ISO-8601; the first is ISO-8601 without the T. Considering the strange formats you can get in JSON, it looks like you've been let off pretty lightly!
Serialization formats aren't meant to be user-friendly, particularly - they're meant to be machine-to-machine formats.
I would hope that JSON.NET would give you a DateTime after parsing; it should only be giving you the ISO-8601 format after you've converted back to JSON.
If you've got a DateTime that you want to format for user consumption, there are all kinds of options with standard and custom format strings. Don't forget that you should respect the culture of the user, as far as possible - so make sure you're taking appropriate steps to either set the thread's current culture to be the user's one, or that you're passing the culture explicitly to DateTime.ToString etc.
You can try it in C#:
.ToString("MMM d yyyy, h:mm tt")

current date format

Is there any way to find the current format of date in the time zone? I am retrieving date in the form of string from database and in case the current datetime format does not match, crash comes, "String was not recognized as valid datetime"
It sounds like what's important isn't the current format of the date as your code understand it, but as it gets it from the database. Why is it in the database as a string to start with? If at all possible you should make it an appropriate date/time related field in the database and make the driver do the conversion.
If that's not possible, you should perform the conversion in your code using a custom date/time format which matches what the server gives you, and in an appropriate culture (quite possibly the invariant one).
The DateTime.Parse method uses the format that is set on the executing thread. See the Thread.CurrentCulture to retrieve the CultureInfo that use used when parsing. The CultureInfo.DateTimeFormat returns the format you are looking for.
If you know the format, you should use the DateTime.ParseExact method to parse the input string with a known format.
Sound like you need to use the DateTime.TryParse-method:
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
If you don't know in which format the date is passed and .NET can't figure it out I think your out of luck. You could of cause try to see if you could figure out the format by yourself by using regex.

Categories

Resources