Home > Software design >  Format Localized DateTime C#
Format Localized DateTime C#

Time:10-19

I want to format localized date into format. e.g yyyyMMdd OR ddMMyyyy OR MMddyyyy based on system date format. Below is what I have tried and it is working , but need efficient way to do same.

DateTime.Now.ToLocalTime().Date.ToString().Replace("/","").Replace(":","").Replace(" ","").Replace("-","")

CodePudding user response:

You can use the ToString overload(read also):

DateTime.Now.ToLocalTime().ToString("yyyyMMdd")

(why you think you need ToLocalTime here? Now always returns the local time)

cant use .ToString("yyyyMMdd") because i need different result depending on what my system date format is. if system date time is dd-MM-yyyy i want ddMMyyyy, if its yyyy-MM-dd then expected result is yyyyMMdd

Then you either stick with your current approach or use something like this:

DateTime.Now.ToString("d").Replace(DateTimeFormatInfo.CurrentInfo.DateSeparator, "")
  • Related