Convert datatable date into dd/mm/yyyy format in asp.net

10,165

Solution 1

Convert and then represent as you want:

  strInvoice_date = Convert.ToDateTime(dt.Rows[i]["INVOICE_DATE"]).ToString("dd/MM/yyyy");

Solution 2

Your dt.Rows[i]["INVOICE_DATE"] retuns object and when you call ToString method, it will call object.ToString() not DateTime.ToString().

If your INVOICE_DATE column is DateTime in your datatable, you can explicitly cast your object to DateTime and use dd/MM/yyyy (I assume you want months instead of minutes) format with a proper culture like InvariantCulture.

var Invoice_date = (DateTime)dt.Rows[i]["INVOICE_DATE"]
                               .ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

If your INVOICE_DATE column is string in your datatable, you need to get it's string representation with object.ToString, parse it to Datetime, and generate it's string representation.

var Invoice_date = DateTime.ParseExact(dt.Rows[i]["INVOICE_DATE"].ToString(), 
                                      "dd-MM-yyyy hh:mm:ss tt", 
                                       CultureInfo.InvariantCulture)
                          .ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Share:
10,165
ash060
Author by

ash060

Updated on June 29, 2022

Comments

  • ash060
    ash060 almost 2 years

    I have a datatable in which I want to get the date in dd/mm/yyyy format.

    Currently I get date like

    02-01-2012 12:00:00 AM

    Below is my code

    strInvoice_date = dt.Rows[i]["INVOICE_DATE"].ToString();
    
  • ash060
    ash060 about 8 years
    getting error as no overload for method takes 1 arguments
  • Soner Gönül
    Soner Gönül about 8 years
    dt.Rows[i]["INVOICE_DATE"] returns object and there is no overload for object.ToString() that takes string as a parameter.
  • JENKINS J
    JENKINS J about 8 years
    You need convert the column with DateTime. strInvoice_date = Convert.ToDateTime(dt.Rows[i]"INVOICE_DATE"].ToString("0:dd/‌​MM/yyyy"));
  • Soner Gönül
    Soner Gönül about 8 years
    I think generally it would be better to use ParseExact in this kind of cases because this format might not be a standard date and time format for OP's CurrentCulture since Convert.ToDateTime(object) probably calls ToString method inside of it. But since OP selected this as an answer, it is not valid for this case :)
  • Hugo Yates
    Hugo Yates about 8 years
    This is the better way to go, to save headaches it's important to define the culture info.