C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Change DateTime To A Friendly Name
WhatsApp
David Mccarter
8y
7.3
k
0
10
25
Blog
Here is a simple extension method to convert a DateTime type to a friendly name like "Today" or "Yesterday," as you see in some file browsers.
public
static
string ToFriendlyDateString(
this
DateTime input)
{
var
formattedDate = string.Empty;
if
(input.Date == DateTime.Today)
{
formattedDate = nameof(DateTime.Today);
}
else
{
formattedDate = input.Date == DateTime.Today.AddDays(-1) ?
"Yesterday"
:
input.Date > DateTime.Today.AddDays(-6) ?
input.ToString(
"dddd"
).ToString() :
input.ToString(CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern,
CultureInfo.CurrentCulture);
}
formattedDate +=
" @ "
+ input.ToString(CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern,
CultureInfo.CurrentCulture).ToLower();
return
formattedDate;
}
You can find this code and lots more in my
dotNetTips.Utility
open source project.
DateTime
Up Next
Unix Time to System.DateTime and Vice Versa
Ebook Download
View all
Coding Principles
Read by 2.8k people
Download Now!
Learn
View all
McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!
Membership not found