Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DateTime to string [duplicate]

Tags:

c#

.net

datetime

I want to convert DateTime to String.

check the below code.

namespace TestDateConvertion
{
    class Program
    {
        static void Main(string[] args)
        {
            object value = new DateTime(2003,12,23,6,22,30);
            DateTime result = (DateTime)value;
            Console.WriteLine(result.ToString("dd/MM/yyyy"));
            Console.ReadLine();
        }
    }
}

I have changed my system date format to Faeroese.

and I am getting the output as

23-12-2013

How should I get the output as ?

23/12/2013

And consider this another scenario, suppose, i have a Customculture Info , and i want to convert my date w.r.t my custom culture, what i was doing before was as follows,

string.Format(customCulture, "{0:G}", result);

now how shall i get the datetime in string using customCulture and it should not depend on system DateTime?

like image 529
Nomesh Gajare Avatar asked Jul 08 '13 12:07

Nomesh Gajare


3 Answers

Looks like your culture's date separator is - and as Tim pointed, / replaces itself with it.

You should use CultureInfo.InvariantCulture as a second parameter in your result.ToString() method.

Gets the CultureInfo object that is culture-independent (invariant).

object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));

Output will be;

23/12/2003

Here a DEMO.

like image 105
Soner Gönül Avatar answered Oct 06 '22 14:10

Soner Gönül


Try this one

Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
like image 24
Kamil Budziewski Avatar answered Oct 06 '22 15:10

Kamil Budziewski


You need to add this

Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));

Now your Code becomes

object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
Console.ReadLine();

NOTE *Add using System.Globalization;*

like image 21
Usman Avatar answered Oct 06 '22 14:10

Usman