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));
Related
This Code produces the output in the comments bellow each Console.WriteLine statement.
Can anyone explain this kind of behaviour?
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("M"));
// Displays August 18
Console.WriteLine(date1.ToString("M "));
// Displays 8
Console.WriteLine(date1.ToString("(M)"));
// Displays (8)
Console.WriteLine(date1.ToString("(M) MMM, MMMM"));
// Displays (8) Aug, August
Can anyone explain this kind of behaviour?
Yes, it's completely documented in standard date and time format strings and custom date and time format strings.
Let's go through them one at a time:
date1.ToString("M"): That uses a single character 'M', so it's the standard format string for "month/day pattern"
date1.ToString("M "): That uses a format string with two characters, so it's a custom format string using M which is the month number, 1-12 with no padding.
date1.ToString("(M)"): Again, a custom format string using M
date1.ToString("(M) MMM, MMMM"): A custom format string using M, as well as MMM ("abbreviated name of the month") and MMMM (" full name of the month")
The important difference between the first two is that a format string is only considered to be a standard format if it's a single character. Otherwise, it's considered to be a custom format. If you want to use a single-character custom format specifier on its own, you can use % as a leading character - so date1.ToString("%M") would return "8" rather than "August 18".
Date and Time in C# are handled by DateTime struct in C# that provides properties and methods to format dates in different datetime formats.
M-> Month number(eg.3)
MM-> Month number with leading zero(eg.04)
MMM-> Abbreviated Month Name (e.g. Dec)
MMMM-> Full month name (e.g. December)
https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
The code is
time.ToString("yyyyMMddHmmsFFF"));
And it returns "20190121153530" with leading zero after 2019.
How do I format the date to get "2019121153530" without the leading zero?
MM in the format you specified will use "The month, from 01 through 12".
M in the format will use "The month, from 1 through 12". Such as:
time.ToString("yyyyMddHmmsFFF"));
See "Custom Date and Time Format Strings" for more options on DateTime string formatting.
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 %.
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 recently switch from using S.DS namespace (which uses ADSI) to the S.SD.Protocol namespace. The only problem is that ADSI handled the conversion of Generalized-Time to a DateTime for me. Now I'm getting back a value of "20070828085401.0Z" for the WhenChanged attribute. DateTime.Parse() will not convert this so is there another way?
The format you are getting is close to the round trip date time pattern ("o") and universal sortable round trip date time pattern ("u") standard date time format strings as described here.
One kludgy solution would be to massage the string you get to fit the pattern and then use the "o" or "u" standard format string with ParseExact.
A better way would be to construct a custom format string that matches the data you are already getting. In the "How Standard Format Strings Work" section of the standard date time format strings page you'll see the full custom formatting strings equivalent to "o" and "u". That should give you a good start.
EDIT: Add code
string format = "yyyyMMddHHmmss.f'Z'";
string target = "20070828085401.0Z";
DateTime d = DateTime.ParseExact(target, format, CultureInfo.InvariantCulture);
In the comments lixonn observes that, using the format string above, ParseExact will not successfully parse a time string like 199412160532-0500.
It also won't parse a number of other valid strings such as times without the trailing 'Zulu' indicator (20070828085401.0); times without a fractional part (20070828085401Z) and times that represent minutes and seconds as a fractional hour (2007082808.90028Z).
The format string can be made slightly more forgiving by replacing the hard-coded 'Z' with the K custom specifier which will accept 'Z', an offset like -0500, and nothing. Whether that additional flexibility is a good thing will depend on your application.
Note that even with the K specifier Lixonn's string won't be parsed successfully since it lacks a fractional part to match the .f component of the format string.
You'll have to use DateTime.ParseExact() specifying the exact format.
You might have to play with the format a little bit but it would be something like this.
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string format="yyyyMMddhhmmss.0Z";
result = DateTime.ParseExact(dateString, format, provider);
You can use datetime's .strptime().
import datetime
# Since 0Z denotes UTC, you can get rid of it and apply the timezone
# later if you would like
time_string = "20070828085401.0Z".split('.')[0]
time_object = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%S")
time_object should output as datetime.datetime(2007, 8, 28, 8, 54, 1). I believe it will be timezone naive, and equivalent to UTC time.
// WIN32 FILETIME is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
// While the unix timestamp represents the seconds since January 1, 1970 (UTC).
private static long Win32FileTimeToUnixTimestamp(long fileTime)
{
//return fileTime / 10000L - 11644473600000L;
return DateTimeOffset.FromFileTime(fileTime).ToUnixTimeSeconds();
}
// The GeneralizedTime follows ASN.1 format, something like: 20190903130100.0Z and 20190903160100.0+0300
private static long GeneralizedTimeToUnixTimestamp(string generalizedTime)
{
var formats = new string[] { "yyyyMMddHHmmss.fZ", "yyyyMMddHHmmss.fzzz" };
return DateTimeOffset.ParseExact(generalizedTime, formats, System.Globalization.CultureInfo.InvariantCulture).ToUnixTimeSeconds();
}