0

str.Replace("/", ",");i need to change the format of my date format

from 30/12/2014 to 30,12,2014.

public void ExportToTxtFile(DataTable dt, string filePath)
        {

StringBuilder str = new StringBuilder();

str.Append(dt.Rows[i][j].ToString() + ",");
}

str.Replace("/", ","); //how to specify only date time format to change

 File.WriteAllText(filePath, str.ToString());

i can use str.Replace("/", ",");

has any good method to specify only date time format can be change?

Michael
  • 51
  • 1
  • 9

3 Answers3

4

If the column you are loading is of DateTime type you should be able to just call the ToString() overload with a custom format such as:

DateTime.Now.ToString("dd,MM,yyyy");
Austin
  • 754
  • 8
  • 12
  • format of database is ("yyyy-MM-dd") i can only retrieve by this way – Michael Jan 05 '15 at 02:23
  • sqlCommand.Parameters.Add(new SqlParameter("@p_Date", dateFrom.ToString("yyyy-MM-dd"))); – Michael Jan 05 '15 at 02:23
  • The displayed format is not necessarily important, what is the actual data type for the database column? DateTime, DateTime2 or NVARCHAR? – Austin Jan 05 '15 at 02:25
  • the db column is DateTime – Michael Jan 05 '15 at 02:38
  • If that is the case you should be able to pass your DateFrom instance directly without having to worry about calling ToString since the ADO.NET framework knows how to correctly handle the datetime type for the target column – Austin Jan 05 '15 at 02:56
  • sqlCommand.Parameters.Add(new SqlParameter("@p_DateFrom", dateFrom.ToString(DateTime.Now.ToString("dd,MM,yyyy")))); ? – Michael Jan 05 '15 at 03:01
  • Assuming that dateFrom has been populated with the correct date sqlCommand.Parameters.Add(new SqlParameters("@p_DateFrom", dateFrom)); – Austin Jan 05 '15 at 03:04
  • qlCommand.Parameters.Add(new SqlParameters("@p_DateFrom", dateFrom)); i will get date with 30/12/2014 format – Michael Jan 05 '15 at 03:07
1

Instead of Replace("/", ","), convert the date using the built-in conversion functionality. Try something like this:

// set the correct culture infos, here from the Netherlands and Spain. Use your cultures ;-)
System.Globalization.CultureInfo sourceCultureInfo =
    new System.Globalization.CultureInfo("nl-NL");
System.Globalization.CultureInfo targetCultureInfo =
    new System.Globalization.CultureInfo("es-ES");

// convert
DateTime sourceDate = DateTime.ParseExact(
    str.ToString(), "dd.MM.yyyy HH:mm:ss", sourceCultureInfo);
string targetDate = sourceDate.ToString(targetCultureInfo)
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
0

You are not assigning the result of the String.Replace(). Try the following:

str = str.Replace("/", ",");
Peter
  • 2,654
  • 2
  • 33
  • 44