get the format of a string date in c# - 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.

Related

How to check for current culture in my ado.net code?

I am trying to parse a date that is coming from a source as "02/11/2013"
In my application, I set the user's culture to either en-CA or en-FR, with their date format's being "dd/MM/yyyy" or "M/d/yyyy"
If I parse the date, and pass in the format, will this work or does it depend on which format I saved to the database?
if (DateTime.TryParseExact(dateString, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern, null, System.Globalization.DateTimeStyles.None, out dtResult))
{
dt = dtResult;
}
I can think properly right now so I need some clarification.
Me passing in the format of "dd/MM/yyyy" or "M/d/yyyy", does this format the date no matter what format the source is in, or is it me telling the datetime parse that the source will be in this format so use this?
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
ADO.NET is strongly typed; there are well known types for storing most data. In the case of dates, that would be DateTime in .NET and datetime in most database systems. If you ever need to worry about culture, then you're already doing it wrong, because you are passing the data around as a string rather than as a DateTime / datetime.
This then renders your concern here redundant:
What I am weary of is that someone is saving to the db in one format, and then a french person wants to read the date and their own format (yes I should be storing in utc).
because a DateTime / datetime has no notion of format - it is simply a date/time value. Any UI presentation / parsing of string data should be completely isolated and specific to the UI. Beyond the UI code you should (when talking about dates/times) be using DateTime / datetime exclusively.
Similarly, when storing an integer you should be using int.
If the date is stored only as "02/11/2013" without any other culture identifying information there is no way for you to know how to properly interpret it! You are absolutely right being worried that somebody with a en-FR culture might save a date to the database as "02/11/2013" meaning the 2nd of November and then somebody with an en-US culture might read that date and interpret it as the 11th of February.
You should only pass the current culture if you know that is relevant, meaning that you know the date string was generated using that culture.
A better approach is to NOT store dates like that in the first place. It's best to store the date in a format that includes timezone as well as format information such as the Internet Date/Time RFC 3339 format.
Or, if you can't, at least make sure to take the date and always convert it to say en-US culture before storing in the database and than pass that culture to the DateTime.Parse when reading from the database.
The .NET XML serialization code for dates can come in handy when serializing/deserializing dates in RFC 3339 format. See this SO post for more info..

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")

convert string in unknown format to date in c#

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats,
eg.
dd/MM/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...
But I need to convert in to a common format - dd/MM/yyyy. The application can run in any windows machines in different culture.
What is the correct way to do it?
EDIT: One more thing I may not know what the format of incoming string.
Thanks in advance.
Use DateTime.ParseExact with the different patterns as formats.
If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.
You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.
As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact.
If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.
Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days.
Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.
The best way is to ask the supplier of those dates for the format.
To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse

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.

Change date to Universal Time Format changes my date wrongly I can't get error

I am trying to simply change the date format from the datatable to universal time format but it formats it wrongly as if I have date for August 7 it changed it to August 8 after formatting it to universal date time. My code for formatting date is,
DateVar[runs] = DateTime.Parse(Convert.ToString(output.Tables[0].Rows[runs][0])).ToUniversalTime().ToString();
Don't get in to code its correct and its a part of loop so "run" is loop and output is data set having one table I have first data in table is "Sunday, August 07, 2011 10:52 PM" and it was converted to "8/8/2011 5:52:00 AM" after implementing universal time format.
Hopes for your suggestions
Universal time isn't a format - it's a time zone, effectively. It's not clear what you're trying to do, but converting a "local" DateTime to "universal" DateTime will usually change the time. If you don't want that to happen, don't call ToUniversalTime.
It's a pity that the .NET date/time API isn't as clear as it could be - the DateTime type itself has some horrible ambiguities about it. I'm trying to improve the situation with my Noda Time project, but you will need to understand what time zones are about etc.
Personally I would suggest not using simply DateTime.Parse or just calling ToString unless you're absolutely sure that the default format is what you want. I usually call DateTime.ParseExact and specify the expected format (and usually CultureInfo.InvariantCulture unless it's a user-entered string) - and likewise I provide a format string to the ToString call.
In your code you're simply converting a string to a string - what are you attempting to accomplish? If you're just trying to change the format (e.g. to dd/MM/yyyyTHH:mm:ss) then you don't need to call ToUniversalTime but you do need to provide the format string.
I suggest you split your code out into several statements to help you debug this (and for general code clarity):
Fetch the string from the DataTable, if you really need to (if it's already a DateTime, there's no point in converting it to a string and then back again)
Parse the string (again, assuming you need to)
Perform any conversions you need to
Format the DateTime with an explicit format string
Now if any single operation is causing a problem, you can isolate it more easily.
If I run ToUniversalTime() from Greenwich it will give same time but if i do it while I live some where else it will get an offset date time object of + or - hours depending on position.

Categories

Resources