如何将 dd/MM/yyyy 中的 DateTime 转换为 dd-MM-yyyy 中的 DateTime?
How to convert DateTime in dd/MM/yyyy to DateTime in dd-MM-yyyy?
关于日期时间格式转换,我在这里经历了很多问题和答案。几乎所有都与将格式转换为字符串输出有关。
现在我想将本地格式 (dd/MM/yyy) 的 DateTime 变量转换为 dd-MM-yyyy[= 格式的 DateTime 变量36=] 格式,用于将其作为 API 方法的输入参数提供。
我尝试了几种方法,比如在解析时提到 InvariantCulture 等等。甚至还尝试使用希伯来日历来设置当前文化。一切都以本地格式 (dd/MM/yyyy) 本身返回日期时间,并且在向 API 提供该日期时间变量时返回错误消息,以仅提供 dd-MM-yyyy 格式的日期时间。
有没有办法将日期时间变量转换为特定格式?
编辑:
有什么方法可以将日期时间转换为特定格式吗?我在下面附上一些屏幕截图以供参考。
我用的是第三方API,不想公开方法
Method structure
Error response from the API method
现在我希望现在有为 DateTime 变量指定格式的方法。
我使用 ToString 方法并为参数提供模式。
例如:
DateTime.Now.ToString("dd-MM-yyyy")
首先 - DateTime
没有一些格式。 string
表示DateTime
可以有格式。
要将 DateTime
转换为 string
的特定格式,您可以使用 ToString()
方法:
DateTime dt = DateTime.Now;
string date = dt.ToString("dd-MM-yyyy");
要将 string
解析为 DateTime
,您可以使用 ParseExact()
方法:
string date = "02/03/2017";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
or
string date = "02-03-2017";
DateTime dt = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
供您编辑:
没有 CultureInfo
的 Convert.ToDateTime()
尝试使用您的 PC
文化将 string
转换为 DateTime
。如果你想使用 Convert.ToDateTime()
使用接受 string
和 culture:
的重载方法
DateTime dt = Convert.ToDateTime(someDate, CultureInfo.InvariantCulture);
关于日期时间格式转换,我在这里经历了很多问题和答案。几乎所有都与将格式转换为字符串输出有关。
现在我想将本地格式 (dd/MM/yyy) 的 DateTime 变量转换为 dd-MM-yyyy[= 格式的 DateTime 变量36=] 格式,用于将其作为 API 方法的输入参数提供。
我尝试了几种方法,比如在解析时提到 InvariantCulture 等等。甚至还尝试使用希伯来日历来设置当前文化。一切都以本地格式 (dd/MM/yyyy) 本身返回日期时间,并且在向 API 提供该日期时间变量时返回错误消息,以仅提供 dd-MM-yyyy 格式的日期时间。
有没有办法将日期时间变量转换为特定格式?
编辑:
有什么方法可以将日期时间转换为特定格式吗?我在下面附上一些屏幕截图以供参考。
我用的是第三方API,不想公开方法
Method structure
Error response from the API method
现在我希望现在有为 DateTime 变量指定格式的方法。
我使用 ToString 方法并为参数提供模式。
例如: DateTime.Now.ToString("dd-MM-yyyy")
首先 - DateTime
没有一些格式。 string
表示DateTime
可以有格式。
要将 DateTime
转换为 string
的特定格式,您可以使用 ToString()
方法:
DateTime dt = DateTime.Now;
string date = dt.ToString("dd-MM-yyyy");
要将 string
解析为 DateTime
,您可以使用 ParseExact()
方法:
string date = "02/03/2017";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
or
string date = "02-03-2017";
DateTime dt = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
供您编辑:
没有CultureInfo
的 Convert.ToDateTime()
尝试使用您的 PC
文化将 string
转换为 DateTime
。如果你想使用 Convert.ToDateTime()
使用接受 string
和 culture:
DateTime dt = Convert.ToDateTime(someDate, CultureInfo.InvariantCulture);