C# 设置日期时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15407499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:43:03  来源:igfitidea点击:

Set DateTime format

c#datetimeformat

提问by Ebikeneser

I have the following code -

我有以下代码 -

DateTime timeStamp;

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

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

哪里y.InnerText11/03/2013 11:35:24

However this is breaking my import statement as it the database is looking for the format -

然而,这打破了我的导入语句,因为数据库正在寻找格式 -

2013-03-11 11:35:24

How can I set the format of the DateTime object?

如何设置 DateTime 对象的格式?

采纳答案by Jon Skeet

How can I set the format of the DateTime object?

如何设置 DateTime 对象的格式?

You can't. DateTimevalues don't haveformats, any more than intor doublevalues do. When you want to convert them to/from strings, that'swhere you specify any formatting information.

你不能。DateTime值不具有格式,任何超过intdouble价值观做。当你想将它们转换为/从字符串,这是在那里你指定的任何格式的信息。

Instead, you should use parameterized SQL and avoid converting the DateTimevalue back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:

相反,您应该首先使用参数化 SQL 并避免将DateTime值转换回字符串。这是一般的最佳实践 - 不要在 SQL 字符串中包含值;参数化 SQL 有多种好处:

  • It avoids SQL injection attacks
  • It avoids conversion issues like this one
  • It keeps your code (SQL) separate from your data (parameter values)
  • 避免SQL注入攻击
  • 它避免了这样的转换问题
  • 它使您的代码 (SQL) 与您的数据(参数值)分开

I would alsosuggest that instead of using Convert.ToDateTime, you specify your expected format when parsing. For example:

建议Convert.ToDateTime您在解析时指定您期望的格式,而不是使用。例如:

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

Basically, the two rules I try to apply are:

基本上,我尝试应用的两条规则是:

  • Avoid performing anyconversions where you don't have to. If you make sure that every system uses the right data types as far as possible, you often don't need to make any conversions at all.
  • Where you doneed to convert to/from string representations, be very explicit about the representation you want to consume/produce. For machine-readable values, that should usually use the invariant culture and possibly a custom date/time format. For human-readable values, that should usually use the user's culture and a standard date/time format.
  • 避免在不必要的地方执行任何转换。如果您确保每个系统都尽可能使用正确的数据类型,那么您通常根本不需要进行任何转换。
  • 在您确实需要在字符串表示之间进行转换时,请非常明确地说明您想要使用/生成的表示。对于机器可读的值,通常应该使用不变区域性和可能的​​自定义日期/时间格式。对于人类可读的值,通常应该使用用户的文化和标准的日期/时间格式。

回答by Akrem

you can use ToString convertion to 2013-03-11 11:35:24

您可以使用 ToString 转换为 2013-03-11 11:35:24

 DateTime timeStamp;

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

回答by JSJ

if you are passing datetime to sql database try with yourdatetime.ToString("yyyy/MM/dd") format this will work for you.

如果您将日期时间传递给 sql 数据库,请尝试使用 yourdatetime.ToString("yyyy/MM/dd") 格式,这对您有用。

and one more thing you can add a datetime format for your Applicaton culture. so this will treat you datetime format at you desire.

还有一件事,您可以为您的应用程序文化添加日期时间格式。所以这将按照您的意愿对待您的日期时间格式。

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);
        }
    }
}

回答by Kaf

Basically Date does not have a format. If the database parameter/fieldis Datetime typeyou should be fine passing as a Date type. It is not a good idea to pass date as a string.

基本上日期没有格式。如果数据库parameter/fieldDatetime type你应该可以作为 Date 类型传递。将日期作为字符串传递不是一个好主意。

However, if that something you have to deal with, then you better pass the Date in a none culture specific date format(ISO8601 or ISO) in a parameterised query. Otherwise you could have problems with database servers in different culture settings.

但是,如果您必须处理那件事,那么您最好none culture specific date format在参数化查询中将日期传递到(ISO8601 或 ISO)中。否则,您可能会遇到不同文化设置中的数据库服务器问题。

For example, for sql server, it is safe (in conversion) to pass date time in ISO8601 as;

例如,对于 sql server,将ISO8601 中的日期时间传递为安全(在转换中);

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

回答by Alex_Spas

And what if you just override your ToString() method of your DateTime object? Wouldn't you be able then to choose the format you want and every time it is used, it will be formatted in the way you want it without being bothered by it.

如果您只是覆盖 DateTime 对象的 ToString() 方法会怎样?难道你不能选择你想要的格式吗?每次使用它时,它都会按照你想要的方式进行格式化而不会被它打扰。

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

这只是一个想法,所以我不知道是否有更好的解决方案。

You can then use the properties year, month, day, to build it like you want. Something like:

然后,您可以使用属性年、月、日来根据需要构建它。就像是:

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

Greetings

你好

回答by Thitiwut Natesang

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

我使用这一步 1. 转换为 DateTime。2. 使用ToString(); 功能

Example :

例子 :

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