Getting day suffix when using DateTime.ToString()
As a reference I always use/refer to [SteveX String Formatting] 1
and there doesn't appear to be any "th" in any of the available variables but you could easily build a string with
string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));
You would then have to supply a "st" for 1, "nd" for 2, "rd" for 3, and "th" for all others and could be in-lined with a "? :" statement.
var now = DateTime.Now;
(now.Day % 10 == 1 && now.Day % 100 != 11) ? "st"
: (now.Day % 10 == 2 && now.Day % 100 != 12) ? "nd"
: (now.Day % 10 == 3 && now.Day % 100 != 13) ? "rd"
: "th"
How can i format 07/03/2012 to March 7th,2012 in c#
You can create your own custom format provider to do this:
public class MyCustomDateProvider: IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!(arg is DateTime)) throw new NotSupportedException();
var dt = (DateTime) arg;
string suffix;
if (new[] {11, 12, 13}.Contains(dt.Day))
{
suffix = "th";
}
else if (dt.Day % 10 == 1)
{
suffix = "st";
}
else if (dt.Day % 10 == 2)
{
suffix = "nd";
}
else if (dt.Day % 10 == 3)
{
suffix = "rd";
}
else
{
suffix = "th";
}
return string.Format("{0:MMMM} {1}{2}, {0:yyyy}", arg, dt.Day, suffix);
}
}
This can then be called like this:
var formattedDate = string.Format(new MyCustomDateProvider(), "{0}", date);
Resulting in (for example):
March 3rd, 2012
Formatting dateTime with suffix
Your problem is that you're passing date.Month
(an int) instead of date
(a DateTime) when formatting the string:
string.Format("{0}{1} {2:MMMM} {3}", date.Day, suffix, date.Month, date.Year)
This makes sense:
date.ToString("MMMM");
This does not:
date.Month.ToString("MMMM");
You should be able to just drop the .Month
off of the argument you're passing in to fix your problem:
string.Format("{0}{1} {2:MMMM} {3}", date.Day, suffix, date, date.Year)
How to convert datetime field to string like 1st Feb 2011?
First of all, 2/1/2011
can be 1st Feb or 2nd Jan not 1st Jan.
Second, let's parse your string
to DateTime
.
DateTime dt = DateTime.ParseExact(dt.Rows[0]["DOJ"].ToString(),
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
or you can explicitly cast it to DateTime
DateTime dt = (DateTime)dt.Rows[0]["DOJ"];
Third, .NET does not have a built-in way in BCL to generate day suffix. But Lazlow write a method for that which works seems okey to me as;
static string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
and you can this method like;
string DateOfJoin = String.Format("{0}{1} {2}",
dt.Day,
GetDaySuffix(dt.Day),
dt.ToString("MMM yyyy", CultureInfo.InvariantCulture));
which generates
DateTime.ToString() format that can be used in a filename or extension?
You can use this:
DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
DateTime.ToString removes slashes
You might need to provide a culture for your to string.
DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
How to convert datetime field to string like 1st Feb 2011?
First of all, 2/1/2011
can be 1st Feb or 2nd Jan not 1st Jan.
Second, let's parse your string
to DateTime
.
DateTime dt = DateTime.ParseExact(dt.Rows[0]["DOJ"].ToString(),
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
or you can explicitly cast it to DateTime
DateTime dt = (DateTime)dt.Rows[0]["DOJ"];
Third, .NET does not have a built-in way in BCL to generate day suffix. But Lazlow write a method for that which works seems okey to me as;
static string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
and you can this method like;
string DateOfJoin = String.Format("{0}{1} {2}",
dt.Day,
GetDaySuffix(dt.Day),
dt.ToString("MMM yyyy", CultureInfo.InvariantCulture));
which generates
How can I parse a date string containing 17th or similar suffixes?
You have the ability to add multiple format for your parse.
Dim formats() As String = {"dd MMMM yyyy", "dd\s\t MMMM yyyy", "dd\t\h MMMM yyyy"}
d = DateTime.ParseExact(s, formats, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)
DateTime.toString shows with time when output to Email
I just ran this code and it outputs exactly what you you want:
You can also use ToString("d")
, which will output 28.10.2014
(based on your culture), or ToShortDateString()
, which will output the same.
Related Topics
"There Was an Error Running the Selected Code Generator" in VS 2013 Scaffolding
"Parameter Not Valid" Exception Loading System.Drawing.Image
Play and Wait for Animation/Animator to Finish Playing
The Provided Uri Scheme 'Https' Is Invalid; Expected 'Http'. Parameter Name: Via
Creating Wcf Channelfactory<T>
Using Itextsharp to Extract and Update Links in an Existing PDF
How to Set the Default Xml Namespace for an Xdocument
How to Set Timer Resolution from C# to 1 Ms
What Is the Worst Gotcha in C# or .Net
Are There Any Suggestions for Developing a C# Coding Standards/Best Practices Document
Super-Simple Example of C# Observer/Observable with Delegates
How Can a Windows Service Start a Process When a Timer Event Is Raised
Removing Nodes from an Xmldocument
How to Get and Set the Window Position of Another Application in C#