Set DateTime format

I have the following code -

DateTime timeStamp;

timeStamp = System.Convert.ToDateTime(y.InnerText);

Where y.InnerText 11/03/2013 11:35:24.

However, this violates my import statement, as it is looking for the format -

2013-03-11 11:35:24

How to set the format of a DateTime object?

+5
source share
6 answers

How to set the format of a DateTime object?

You can not. Values DateTimehave no formats, no more than intor double. When you want to convert them to / from strings, you specify formatting information.

Instead, you should use parameterized SQL and not convert the value DateTimeback to a string in the first place. This is a general recommendation - do not include values ​​in the SQL string; Parameterized SQL has several advantages:

, Convert.ToDateTime . :

timeStamp = DateTime.ParseExact(y.InnerText,
                                "dd/MM/yyyy HH:mm:ss",
                                CultureInfo.InvariantCulture);

, , , :

  • - , . , , , .
  • / , , /. , , , . , /.
+13

datetime sql, yourdatetime.ToString( "yyyy/MM/dd" ), .

, Applicaton. datetime .

using System;
using System.Globalization;
using System.Threading;

namespace test {
    public static class Program {
        public static void Main() {
            CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            culture.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd HH:mm:ss";
            culture.DateTimeFormat.LongTimePattern = "";
            Thread.CurrentThread.CurrentCulture = culture;
            Console.WriteLine(DateTime.Now);
        }
    }
}
+1

ToString 2013-03-11 11:35:24

 DateTime timeStamp;

 timeStamp = System.Convert.ToDateTime(y.InnerText).ToString("yyyy-MM-dd HH:mm:ss");
0

. parameter/field Datetime type, . .

, -, none culture specific date format (ISO8601 ISO) . .

, sql ( ), ISO8601 ;

'yyyy-mm-ddThh:mi:ss.mmm' //(no spaces)
0

So what if you just override your ToString () method of a DateTime object? Could you then choose the desired format and each time it is used, it will be formatted the way you want, without worrying about it.

This is just a thought, so I don’t know if there are better solutions or not.

Then you can use the year, month, day properties to build it however you want. Sort of:

public override ToString(){
   return this.Year + "-" + this.Month + "-" + this.Day;
}

Hi

0
source

I use this step 1. Convert to DateTime. 2. Use ToString (); Function

Example:

 DateTime myDateTime = DateTime.Now;
 string myDateTimeString = myDateTime.ToString("yyyy-mm-dd hh:mm:ss");
0
source

All Articles