DateTime.ToString formatting - c#

I'm displaying localized short dates by providing culture info to DateTime.ToString method. By now I was using
x.ToString("d", ci); // 23.12.2000
that displays short date. But now I would like to also include abbreviated day name. I tried
x.ToString("ddd d", ci); // pon 23
but now d becomes day specifier instead of short date format so instead of day name and short date I only get day name and day number.
How do I convince formatter to display day along with predefined culture short date format?

How about:
string.Format(ci, "{0:ddd} {0:d}", x)

The "standard" formatting strings work by obtaining the equivalent property of the CultureInfo's DateTimeFormat. In this case "d" finds the ShortDatePattern property, which will be something like "dd.MM.yyyy", "dd/MM/yyyy", "MM/dd/yyyy", "yyyy-MM-dd" and so on, depending on that locale in question.
Hence you can make use of it in a custom pattern like so:
x.ToString("ddd " + ci.DateTimeFormat.ShortDatePattern, ci) // Sat 2000-12-23 on my set up, should presumably be pon 23.12.2000 on yours

x.ToString("ddd ", ci) + x.ToString("d", ci);

If nothing else, you could: x.ToString("ddd", ci) + " " + x.ToString("d", ci);

Take a look at this explanation:
http://www.csharp-examples.net/string-format-datetime/
Maybe you can find some examples there.
Update
As response to the comment, Example 3 in the first codeblock clearly states how to do this:
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
Googling a question about date to string formatting, and hitting this question will be much more valuable if there is a reference to good examples. Hence the reference to the csharp-examples site.

Related

Formatting Date with abbreviated month, while adhering to culture date structure

Developing a multilanguage application, and trying to format a DateTime object to string within a limited space in a table. Full month names might be too long, so we have to use abbreviations.
Some cultures have the format "Oct 12", some have "12. okt" and so on.
The standard .ToString("m") is almost what I want, but with abbreviations:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#MonthDay
Similar question, but the answer won't work for us, as this dictates the order of month and day:
Formatting Date String abbreviating month
Is there any way of getting the overall structure of a culture's date formatting, like order of day and month, with or without "." after the number etc? Or another way of generating the required string? This feels like it should be fairly straight forward, as all the pieces are already present.
As per the documentation you linked, the custom date and time format "m" is defined by a CultureInfo's DateTimeFormat.MonthDayPattern property. So I'd look that up for the current culture and customize the format string. Then use the modified format string with ToString.
I was able to solve this myself using the culture's DateTimeFormat wich provides a MonthDayPattern. By simply replacing "MMMM" with "MMM" this will solve the challenge, at least for the locales that we plan to support. I have not tested with all possible locales.
(I know it won't work for "ja-JP", wich has special characters in their pattern)
DateTime date = DateTime.Now;
CultureInfo culture = new("en-US", false);
DateTimeFormatInfo dateTimeFormat = culture.DateTimeFormat;
string pattern = dateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM");
string formatted = date.ToString(pattern, culture);
The pattern for "en-US" goes from "MMMM d" to "MMM d" giving "Oct 13"
The pattern for "nb-NO" goes from "d. MMMM" to "d. MMM" giving "13. okt."

Print a DateTime with the same culture format as it was parsed from but with a shorter year component

There are many different ways of representing dates, based on the culture you're using.
Let's say I take the US date for January 2nd, 2018: "1/2/2018".
I want to make a method that returns the same value in the same culture format but with only two digits for the year component.
For example:
dd/mm/yyyy -> dd/mm/yy
mm/dd/yyyy -> mm/dd/yy
yyyy-mm-dd -> yy-mm-dd
I want to take a DateTime variable and return the same date variable in the same culture but with the year in the format yy.
Is it ok for every culture if i do something like this?
var year = mydate.ToShortDate.ToString("yy");
var date = mydate.ToShortDate.Substring(0, mydate.Count() - 4) + year;
My input will be .ToShortDate() in many cultures
There is no proper way to do this as far as I know, so the following should be considered a hack.
Let's assume that the date is held in a DateTime. How it got there is not important.
Now the task is to convert it to a string representation according to the short date format, whatever that might be, but with yyyy instead of yy.
http://www.basicdatepicker.com/samples/cultureinfo.aspx
It looks like short date formats contain either yyyy or yy in pretty much all cultures, so let's make that assumption.
The conversion can now be done in this way.
var sampleDate = new DateTime(1992, 12, 31);
var formatString = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
var newFormatString = formatString.Replace("yyyy", "yy");
var sampleDateAsString = sampleDate.ToString(newFormatString);
If the original format string does not contain "yyyy", then the new format string will be the same as the original.
Of course you can get the ShortDatePattern for any culture, not only the current culture as shown here.

date month not displaying correctly

why is
string date = string.Format("{0:mmddyyHHmmss}",
DateTime.Now);
giving me 420813104204
shouldn't it be 040813... ?
I am trying to match
mmddyyHHmmSS
You need to use MM for month not mm, mm is for minutes not months.
string date = string.Format("{0:MMddyyHHmmss}",
You can find more about formats here.
try this instead
string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);
string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);
would give you the required format.
Check out this link for reference
That's because mm is for the minute not months, you need to use MM. You can see the definition for custom date time strings here.
string date = string.Format("{0:MMddyyHHmmss}",
Further, I generally don't use string.Format with DateTime objects because I've seen some anomalies when it comes to parsing them across different cultures. Leveraging the ToString method on the DateTime object for me has always been more reliable. That's just something I've seen - it also could be that I was doing something wrong with the string.Format. I wish I could build an example of that right now but I don't even remember what those anomalies are now - I just remember having problems so I switched.

want to convert datetime to format like mm/yyyy

I want to grab the datetime object in string form such as "mm/yyyy"
ViewBag.Created = d.item.StartDate.ToString("mm/yyyy");
but I am getting string as 10-2012. Please help me to overcome this issue.
Format for month, should be in MM, mm is for minutes
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
mm is minutes, and / is the culture-specific date separator. It sounds like in the current culture, - is the date separator. I suspect you want MM/yyyy, using the invariant culture, which has / as the separator:
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the slash:
ViewBag.Created = d.item.StartDate.ToString("MM'/'yyyy");
Note that this difference can also change the month and year figures, if the current culture uses a non-Gregorian calendar.
See the MSDN page on custom date and time format specifiers for more details.
Are you certain that you want to fix the format for all cultures though? It's unfortunate that there's no way of saying "give me a culture-appropriate month-and-year format" but you at least need to be aware that it might look odd to some people.
you can use
ViewBag.Created = d.item.StartDate.ToString(#"MM\/yyyy");

Date format pattern

Setting format for the date
#String.Format("{0:D}", Model.Date)
Code above shows the date in the following format: (13 January 2012)
The required output: (Friday 13 January 2012)
Is there a format for this pattern?
Yep, here you go.
String.Format("{0:dddd d MMMM yyyy}", Model.Date)
Full MSDN Documentation
The general rule I use to remember these formats is like this:
one character means the number alone;
two characters means add a leading zero if necessary
three characters means use three letters if day or month, four numbers for year
four letters means use full word for day or month
Extra stuff (not special characters) just gets put in the string
e.g. Consider 1st Jan 2001
String.Format("{0:(d;dd;ddd;dddd),(M;MM;MMM;MMMM),(y,yy,yyy,yyyy)}", DateTime.Parse("2001/01/01"))
will return
(1;01;Mon;Monday),(1;01;Jan;January),(1,01,2001,2001)
Similar rules for times, like this:
String.Format("{0:(h;hh):(m;mm):(s,ss) (t,tt)}", DateTime.Now)
to give this:
(9;09):(41;41):(34,34) (P,PM)
DateTime now = DateTime.Now;
Console.WriteLine(String.Format("{0:dddd d MMMM yyyy}",now));
//output = Friday 13 January 2012
if you want the standard date format just use
Console.WriteLine(now.ToString("D"));
here is something I wrote real quick as well to help you in the future if you want to see what you can to with the now.ToString() in regards to passing formats.
try this out in a Console Application to see the results.. Cheers
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));
Console.Read();
As #Dommer points out String.Format("{0:dddd d MMMM yyyy}", Model.Date) gives you the result you want. And here you'll find MSDN documentation on date and time formats.
If you need to be culturally-aware then use Format(IFormatProvider, String, Object()).
String.Format(CultureInfo.InvariantCulture, "{0:D}", Model.Date);

Categories