Use DateTime Format Strings in a Custom DateTimePickerFormat - c#

Everywhere in my code, when dealing with dates, I rely on the DateTime Format String "G". EXCEPT in the DateTimePicker itself, as I must set a CustomFormat, and the CustomFormat doesn't accept "G" as a valid format specifier. I need this so that the dates will all look the same, independent of culture.
Any thoughts on how I might circumvent this issue?

The following code should work:
picker.CustomFormat = DateTimeFormatInfo.ShortDatePattern + DateTimeFormatInfo.LongTimePattern
This is essentially what the "G" format specifier gives you.

Related

string to dateTime convention changes the format of the string

My code is like this
DateTime dt = new DateTime();
dt= DateTime.ParseExact("14/09/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
I am expecting dt to have a format of dd/MM/yyyy but the output I am getting is in MM/dd/yyyy format.
This is the correct out put I am getting 9/14/2017 12:00:00 AM.
Can anyone please point out what I am doing wrong here?
if you expect the format "dd/MM/yyyy" you need to specify it when displaying the DateTime. To do so you can use this overload of the ToString method:
dt.ToString("dd/MM/yyyy");
A DateTime on it's own has no format. Only the string representation of it has one.
EDIT:
Important remark by Tim Schmelter:
/ is a custom format specifier which replaces all occurences with the local date-separator. You either have to esacape them by embedding them within ' or use CultureInfo.InvariantCulture as second parameter. Read this post
That means either use this:
string str_rep = dt.ToString("dd'/'MM'/'yyyy");
or:
string str_rep = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Your dt is a DateTime, not a string. Format concept only applies when you get their textual (aka string) representation. What you saw is probably what debbuger/ide shows you as a textual representation.
If you get a specific format of your dt, then you can use .ToString() method with dd/MM/yyyy format and a proper culture like InvariantCulture.
string myFormat = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
For beginners, it is really important to understand the difference between what is a DateTime and what is their string representation.
If DateTime.ToString() is resulting in an unexpected format, the likely case is that the current culture isn't being set. By default, the date format used is taken from the host machine. However, you can either specify it directly by setting the thread's CurrentCulture for the culture code you need, or you can set it in your application's configuration file. E.g., a web application's web.config can have a globalization section, like so;
<globalization culture="en-GB" uiCulture="en-GB" />
Alternatively, as already specified, you can set the format explicitly via a custom format string .ToString("dd/MM/yyyy").

Deserialize ISO 8601 date time string to C# DateTime

I'm trying to use:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )
But it gives me a FormatException: Input string was not in a correct format.
What am I doing wrong?
If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:
DateTime value = DateTime.ParseExact(text, "o", null);
The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.
I haven't specified a format provider, as it doesn't matter:
The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.
If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.

Convert date in string to DateTime with same format

I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

datetime.parseexact returns wrong month

Here is my code:
a.dateFrom = DateTime.ParseExact(x, "dd/mm/yyyy", null);
And x has value of: 08/03/2012
However, a.dateFrom has value of 08/01/2012. Why?
You should use MM as format for month
As ionden notes, you should have a format of
"dd/MM/yyyy"
Currently you're parsing the second part as minutes (as that's what mm means).
See the documentation for custom date and time format strings for more information. I'd also strongly encourage you to consider using the invariant culture for parsing - if you're using a custom format string, that usually means you don't want to treat the input in a culture-sensitive fashion at all.

How to convert a string to a specific DateTime format in c#?

How to convert the string "28/09/2009" to DateTime in a specific format?
Ex:
I want to convert "2009-09-28 17:30:40" to DateTime.
I want to convert "28/09/2009 17:30:40" to DateTime.
I want to convert "20090928 17:30:40" to DateTime.
There are multiple possible formats. I tried this:
string[] formats = new string[] {"yyyymmdd","yyyymmddThhmmss","yyyy/mm/dd hh:mm:ss","yyyy/mm/dd","yyyy-mm-dd hh:mm:ss","yyyy-mm-dd"};
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime formattedDate = DateTime.ParseExact(aDate, formats, culture, DateTimeStyles.None);
This example throws an exception with the message "String was not recognized as a valid DateTime".
What's wrong in the code above?
None of your formats put the day first, like this: "dd/MM/yyyy".
Also note the capital 'M', since lower case 'm' is for 'minutes'. You have a similar problem with your hours; since your samples all use 24 hour time you need a capital 'H'.
Your format string array should look like this:
string[] formats = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss"};
Those formats exactly match your supplied sample strings.
Additionally, you probably want to use the invariant culture rather than en-US in this case. Otherwise, the '/' character in your format strings is really a culture-specific date separator, which a user might over-ride on their local system.
Finally, since you're obviously having trouble matching up the strings up, you might want to use TryParseExact(), which works just like parse exact but uses an out parameter rather than returning the value, so that it can return a boolean to indicate success or failure rather than throwing an exception.
See the complete format string reference here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Categories

Resources