-2

This code appears to format the current datetime to a Chinese long format:

var result = DateTime.Parse(Convert.ToString(DateTime.Now, new CultureInfo("zh-tw"))).ToLongDateString();

This code appears to do the same thing but does it by modifying the current thread culture:

Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-tw");
DateTime dtCreateAt = DateTime.Now;
var result = DateTime.TryParse(Convert.ToString(dateTime.Date), out dtCreateAt).ToLongDateString();

Are these snippets, in effect, the same? Should one be used over the other for any reason?

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • 4
    There's little point to taking a date, formatting it to a string, then converting that back into a date, then formatting it back to a string again. –  Aug 14 '19 at 15:52
  • 2
    The snippets are not the same; the first doesn't set the threads culture. –  Aug 14 '19 at 15:53
  • In the first you are applying the formatting to a single instance, whereas in the latter, by modifying the current thread culture, it would apply to any instance. Same result for the one datetime instance but, in effect, not the same at all! – Canica Aug 14 '19 at 16:12
  • What is the shortest method of accessing the ToLongDateString and ToShortDateString methods? The code I posted seems needlessly long in both cases, but I can't find a shorter version. – Matt W Aug 14 '19 at 16:16
  • @amy I know that they are not the same, but to the effect of formatting the date string, they do appear to be. – Matt W Aug 14 '19 at 16:23
  • 2
    Just do `var result = DateTime.Now.ToString("D", new CultureInfo("zh-TW");` as the D format string is the same as long date/time format. – ckuri Aug 14 '19 at 16:29
  • And ToShortDateString() is "d" :) Thanks! – Matt W Aug 14 '19 at 16:49

1 Answers1

0

Why is this particular date being formatted to zh-tw? Is it because you are presenting data to a Taiwanese user? Or because you are writing a file that is sent to a server in Taiwan assuming Taiwanese-formatted dates in its input?

In the former case, it makes sense to change a program-wide setting and affect everything shown to the user.

In the latter case, the culture change should be limited to the smallest block (just one function call) and not change the thread culture setting.

Assign to CurrentThread.CurrentCulture only if you intend to affect all formatting the application does (at least up to the point the user accesses settings and picks a different preference).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I am formatting for Taiwanese users. I understand that the formatting is basically the same output. But the aim is to get to the ToLongDateString and ToShortDateString methods as directly as possible. The single line code appears to be (aside from the thread culture issue) the same. – Matt W Aug 14 '19 at 16:25