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);
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
I am writing a data parser and trying to work out if a field is a number, a date, a string etc.
The .NET DateTime.TryParse is understandably slow when checking many records (as it checks many different date formats). Therefore, I want to shortcut the processing if possible. A simple check I can do initially is look at the length of the string and reject it if it falls outside of some bounds.
The shortest date I think I should reasonably expect is 6 characters long (e.g. d/M/yy) so I can make the following check:
if (fieldValue.Length < 6)
{
// no datetime is shorter than 6 chars (e.g. d/M/yy is the shotest I can think of)
return false;
}
What is the longest string that still represents a parse-able DateTime?
(For example, "Wednesday, 30th September 2020 12:34:56" is pretty long but I bet there are longer examples!)
A few points:
I am not looking for tricksy answers where the date is padded out with white space or something like that.
I am focused on English dates initially but would be interested if other cultures can throw up longer examples.
What is the longest string that still represents a parse-able
DateTime?
Take a look at the list of custom format specifiers for a DateTime, and take all of those into account.
For instance, this:
DateTime dt = DateTime.Now;
string strNow = dt.ToString("dddd, MMMM dd, yyyy gg hh:mm:ss.fffffff tt K");
Console.WriteLine(strNow);
Gives:
Tuesday, June 16, 2020 A.D. 08:47:02.2667911 AM -06:00
But those different types of values can be output differently based on the information in the DateTime. Look CLOSELY at all the different possible outputs for each specifier in the documentation to see what I mean.
Why this line won't work?
DateTime myDate = DateTime.ParseExact("04:05:14:17:17:09", "DD:MM:YY:HH:MM:SS", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
This format is very much not what you're trying to do.
Try changing it to dd:MM:yy:HH:mm:ss:
DateTime myDate = DateTime.ParseExact("04:05:14:17:17:09", "dd:MM:yy:HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
So, what have I changed:
MM refers to months, mm is for minutes
ss needs to be lowercase
dd needs to be lowercase
yy needs to be lowercase
And just for the record, I left HH uppercase because that means it's 24-hour, but lowercase would be 12 hour.
You might want to review the Custom Date and Time Format Strings MSDN page, where all these are explained. It has some good examples that might help you.
I have written the below query to create an xml from entity, I need to get date time in .NET in yyyymmddhhmmss format for the field SLOTTINGTIME, so I have thought of writing a new method to get date time in desired format.
var slottingmessagexml = new XDocument(new XElement("Message",
new XAttribute("ID","SLT"),
new XElement("Record",
new XAttribute("STORENO",slottingmessage.StoreID),
new XAttribute("PICKLOCATION",slottingmessage.PickLocation),
new XAttribute("TPNB",slottingmessage.ProductID),
new XAttribute("SLOTTINGTIME",GetDateTimeInNewFormat(slottingmessage.SlottingDateTime)),
new XAttribute("SLOTTTINGACTION",slottingmessage.SlottingAction))
)
);
You can use
string strDate = DateTime.Now.ToString("yyyyMMddhhmmss");
If 24hr format is required that use uppercase HH inplace of hh in the format string.
Remember the first MM should be in upper case as lower case mm is for minutes where as uppercase is for Month.
For your particular case instead of writing a new method you can do:
new XAttribute("SLOTTINGTIME",slottingmessage.SlottingDateTime.ToString("yyyyMMddhhmmss")),
One more thing to add: The output will contain Hour in 12 hours format because of the lower case hh part in the string. Not really sure if you need that because without AM/PM this can't indicate the accurate time. For that purpose use HH for hours which will display hours in 24 hour format. So your code could be:
new XAttribute("SLOTTINGTIME",slottingmessage.SlottingDateTime.ToString("yyyyMMddHHmmss")),
//^^ for 24 hours format
How about this?
public string GetDateTimeInNewFormat(DateTime d)
{
return d.ToString("yyyyMMddhhmmss");
}
Or, for 24h format:
public string GetDateTimeInNewFormat(DateTime d)
{
return d.ToString("yyyyMMddHHmmss");
}
Although your question does not explicitly say what format you are looking for, I think that based on your example format of yyyymmddhhmmss we can assume that you want [years][months][days][hours][minutes][seconds].
Based on that, we can break each part down as follows:
Years: If you want the full year then your yyyy is correct and will prduce 2013 for example. A common (although not encouraged) alternative could be yy (e.g. 13)
Months: Currently your attempt of mm does not return months. It will produce the minutes. You likely want MM (e.g. 04). Alternative include MMM (e.g. APR) and MMMM (e.g. April)
Days: Again you have this correct already. dd will produce 18 for example.
Hours: Your attempt of hh will produce a 12-hour time format. If this is what you are after then fine. But given that you have not attempted to include an AM/PM designator (with can be done with tt by the way) then I would recommend you opt for the 24-hour format which is HH (upper-case)
Minutes: You are correct with your minutes, mm will produce 52 for example.
Seconds: Again, ss is correct and will produce 33 for example.
Now we can string them all together and produce the following format, which includes the 24-hour time format which I would recommend. This can then be passed to the DateTime objects ToString() function like so:
var stringDateTime = slottingmessage.SlottingDateTime.ToString("yyyyMMddHHmmss");
If you wanted to maintain your approach of the GetDateTimeInNewFormat method, then you can implement it like so:
public string GetDateTimeInNewFormat(DateTime dt)
{
return dt.ToString("yyyyMMddHHmmss");
}
This function would then be called the same way you already have in your example code:
GetDateTimeInNewFormat(slottingmessage.SlottingDateTime)
You can read more information about the various date/time formatting options here where there are plenty of examples
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.