I provide an application where the user is able to format any date by any given format string.
The problem I discovered is the following:
Let's say, I want to format the date as single month index. This is, for today "6".
But:
DateTime.Today.ToString("dd.MM.yyyy") => 26.06.2014<br/>
DateTime.Today.ToString("M") => **26 Juni**<br/>
DateTime.Today.ToString("dM") => 266
Using msdn I found out, that "M" is - if used singular - a standard format specifier, but if used with other chars, its a custom format specifier (http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx; http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx)
Question: How to force interpreting the given format string always as custom format specifier?
In your second case, you need to specify that the M is a custom format specifier by providing the % sign:
Console.WriteLine(DateTime.Today.ToString("%M"));
Prints:
6
According to MSDN: Custom Date and Time Format Strings and MSDN: Using Single Custom Format Specifiers, the % sign:
Defines the following character as a custom format specifier.
I guess if the user can specify the string, you should always escape it with %.
Related
I searched SO to find the answer to this issue, and found "How to add literal strings in a DateTime format?".
I tried the accepted solution, but did not get the result that I expected. My code is below:
DateTime.Now.ToString("'Previously exported on' d 'at' t") which returns "Previously exported on 7 at P"
I had expected it to return "Previously exported on 02/07/2014 at 05:46 PM"
I also tried:
DateTime.Now.ToString("'Previously exported on' f") which returns "Previously exported on 0"
However, if I only use the simple format strings, I get the expected results:
DateTime.Now.ToString("d") returns "02/07/2014"
DateTime.Now.ToString("t") returns "05:46 PM"
DateTime.Now.ToString("f") returns "Friday, February 07, 2014 05:46 PM"
What am I missing? Can the "short" format string NOT be used with the literals?
You can always use the string.Format for this, which allows you to specify the format at each index using { index[,alignment][ :formatString] }. Ie,
string.Format("Previously exported on {0:d} at {0:t}", DateTime.Now);
It looks like the overloaded DateTime.ToString(string format) expects either standard or custom DateTime format string -- it can't accommodate both.
The format parameter should contain either a single format specifier character (see Standard Date and Time Format Strings) or a custom format pattern (see Custom Date and Time Format Strings) that defines the format of the returned string
i am trying to format the date to this format. 01/20/2013 02:30PM EDT, using this
LastModified.ToString("MM/dd/yyyy HH:mmtt");
but the result is coming like this
01-20-2013 02:30PM dont know why it is showing '-' instead '/'.
Also, for timezome, it seems there is only format available like +02:00. But I want timezone as string, i could not find any format for this, how can I get is as string like EDT/PST/IST etc?
From the MSDN page on custom date and time format strings:
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfoDateSeparator property of the current or specified culture.
If you want it to definitely use /, you should either use the invariant culture, or quote the slash ("MM'/'dd'/'yyyy hh':'mmtt"). Note that I've quoted the time separator as well, as that can vary by culture too. I've also changed it to use the 12 hour clock, as per Arshad's answer.
When using a custom date/time format, you should probably use the invariant culture anyway. (For example, it seems odd to use a UK culture to format the string in a US-centric way - today would normally be represented as 02/05/2013 in the UK, not 05/02/2013.)
In terms of a time zone specifier - I don't know any way to use the time zone abbrevation within date/time formatting. I would personally advise against using abbreviations anyway, as they can be ambiguous and confusing. I can't see anything within TimeZoneInfo which even exposes that information for you to manually add it.
(It's possible that in Noda Time we'll support formatting with the abbreviation, but probably not parsing, precisely because of the ambiguity.)
i have found one mistake is that ,HH means time in 24 HRS format. You can try
string date = "01/20/2013 02:30PM";
DateTime dtTime;
if (DateTime.TryParseExact(date, "MM/dd/yyyy hh:mmtt",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
Formatting of DateTime is influenced by your Culture and your format string. Your current culture (Thread.CurrentThread.CurrentCulture) uses the - as the default seperator of your date components.
The Culture of India uses - and since you are from Inda, it would make sence (see: http://en.wikipedia.org/wiki/Date_and_time_notation_in_India)
Two options:
Choose a correct Culture which uses the / by default as seperator. For example: LastModified.ToString("MM/dd/yyyy HH:mmtt", new CultureInfo("en-US"));
Or reformat your format string with the escape character \. For example: For example: LastModified.ToString("MM\/dd\/yyyy HH:mmtt");
See also: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I am trying to display a datetime field using the hour portion only without leading zeros for the single digit hours as in: return string.Format("{0:h}", MyDateTimefield) but I get a "Input string was not in a correct format" error. Why?
return string.Format("{0:hh}", MyDateTimefield) works. Looking for the correct format and not a workaround.
From the pertinent docs:
If the "h" format specifier is used without other custom format specifiers, it is interpreted as a standard date and time format specifier and throws a FormatException. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.
Following that link gets you to:
To use any of the custom date and time format specifiers as the only specifier in a format string […], include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.
From this link using h is the correct format for hour without leading 0. Very interesting.. the following all seem to work:
return string.Format("{0: h}", MyDateTimefield)
return string.Format("{0:h }", MyDateTimefield)
return string.Format("{0:h:m}", MyDateTimefield)
But as soon as you put in return string.Format("{0:h}", MyDateTimefield) it throws an exception.
As for why, I'm not sure. If you're okay with a space the first 2 lines should work.
how can i create time in this format (DATE_ISO8601) in C# ?
2009-05-18T16:34:09.423-0700
thank you!
You can use the O or o format specifier.
DateTime.Now.ToString("O");
From MSDN (Standard Date and Time Format Strings):
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. Strings that are passed to the Parse or ParseExact method must conform exactly to this custom format pattern, or a FormatException is thrown.
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the docs, 'd' should produce the day (1-31).
string.Format("{0:d }", DateTime.Today);
string.Format("{0:d}", DateTime.Today);
UPDATE:Adding % is indeed the trick. Appropriate docs here.
See here
d, %d
The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.
Otherwise d is interpreted as:
d - 'ShortDatePattern'
PS. For messing around with format strings, using LinqPad is invaluable.
From the MSDN documentation for "Custom Date and Time Format Strings":
Any string that is not a standard date
and time format string is interpreted
as a custom date and time format
string.
{0:d} is interpreted as a standard data and time format string. From "Standard Date and Time Format Strings", the "d" format specifier:
Represents a custom date and time
format string defined by the current
ShortDatePattern property.
With the space, {0:d } doesn't match any standard date and time format string, and is interpreted as a custom data and time format string. From "Custom Date and Time Format Strings", the "d" format specifier:
Represents the day of the month as a
number from 1 through 31.
The {0:d} format uses the patterns defined in the Standard Date and Time Format Strings document of MSDN. 'd' translates to the short date pattern, 'D' to the long date pattern, and so on and so forth.
The format that you want appears to be the Custom Date and Time Format Modifiers, which work when there is no matching specified format (e.g., 'd ' including the space) or when you use ToString().
You could use the following code instead:
string.Format("{0}", DateTime.Today.ToString("d ", CultureInfo.InvariantCulture));