Haddar Macdasi
Haddar Macdasi

Reputation: 3555

How to set ToLocalTime date format

I want to set at one place to format to show tostring of datetime/ I want format to be "dd/MM/yyyy HH:mm:ss" every time I write ToString() so it will be the default format . I've tried

CultureInfo ci = new CultureInfo(lang);
ci.DateTimeFormat.LongDatePattern = "dd/MM/yyyy HH:mm:ss";
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name)

without success.

Upvotes: 0

Views: 1779

Answers (5)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

I think this is what you are looking for:

var ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.DateTimeFormat.ShortDatePattern = "dd/mm/yyyy";
ci.DateTimeFormat.LongTimePattern = "hh:mm:ss";
Thread.CurrentThread.CurrentCulture = ci;
Console.WriteLine(DateTime.Now);

Upvotes: 1

geek
geek

Reputation: 616

Try this:

CultureInfo ci = new CultureInfo("en-US");
ci.DateTimeFormat.LongDatePattern = "dd/MM/yyyy HH:mm:ss";
CultureInfo.DefaultThreadCurrentCulture = ci;
CultureInfo.DefaultThreadCurrentUICulture = ci;

Console.WriteLine(CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);
Console.WriteLine(DateTime.Now.ToString("D"));

It's worth to notice that I used DefaultThreadCurrentCulture. You can read more about this here: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.defaultthreadcurrentculture.aspx

Upvotes: 0

Jonny
Jonny

Reputation: 401

 string thetime = DateTime.UtcNow.TimeOfDay.ToString(//yourtimeformat);

this brings the universal time

string thetime = DateTime.Now.TimeOfDay.ToString(//yourtimeformat);

your current system time

Upvotes: 0

ttaaoossuu
ttaaoossuu

Reputation: 7884

Try setting current culture like this:

    Thread.CurrentThread.CurrentCulture = ci;
    Thread.CurrentThread.CurrentUICulture = ci;

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59252

I would suggest you to go with the following.

You can add a extension method like this:

public static class LocalDateTime
{
    public static string ToLocalDateTime(this DateTime dt)
    {
       return dt.ToString("dd/MM/yyy HH:mm:ss");
    }
}

With the above, you can just call datetimeObj.ToLocalDateTime(); instead of ToString() method.

Upvotes: 2

Related Questions