4

I've a datetime:

DateTime dt = new DateTime(2003, 5, 1);
dt.DayOfWeek // returns Thursday

How I can split only first three characters from DayOfWeek e.g. Thu?

2 Answers2

11

If you mean for it to work in different cultures, then your best bet is probably:

var abbr = culture.DateTimeFormat.GetAbbreviatedDayName(dayOfWeek);

where culture is a CultureInfo, for example:

var culture = CultureInfo.CurrentCulture;

In English cultures, this is the 3-letter version:

Sun
Mon
Tue
Wed
Thu
Fri
Sat
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • what if I do same for month? –  Dec 21 '17 at 14:45
  • 5
    @Asif.Ali then: `GetAbbreviatedMonthName` – Marc Gravell Dec 21 '17 at 14:45
  • where should I place if datetime format is `12/21/2017`? –  Dec 21 '17 at 15:00
  • @Asif.Ali what do you mean "where should I place"? you asked specifically for the 3-letter (abbreviated) version of things - the "datetime format" is irrelevant: once parsed, a `DateTime` *does not have* a format; it *does*, however, have a `.Month` and `.DayOfWeek` – Marc Gravell Dec 21 '17 at 15:01
1

Marcs approach is the best here. But if i understand your question in a more general way, how to get the first three letters of an enum-value, you can use string methods if you use enum.ToString:

DateTime dt = new DateTime(2003, 5, 1);
string dow = dt.DayOfWeek.ToString();
dow = dow.Length > 3 ? dow.Remove(3) : dow;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939