我在这里经历了许多有关日期时间格式转换的问题和答案。几乎所有都与将格式转换为String的输出有关。
现在我想将本地格式(dd / MM / yyy)的DateTime变量转换为dd-MM-yyyy 格式的 DateTime变量,以便将其提供为API方法的输入参数。
我尝试了几种方法,例如在解析时提及InvariantCulture和所有方法。甚至尝试使用希伯来日历来设置当前的文化。所有东西都以本地格式(dd / MM / yyyy)本身返回DateTime,并且在向API提供datetime变量时返回错误消息,以便仅以dd-MM-yyyy格式提供日期时间。
有没有办法将datetime变量转换为特定格式?
修改
有没有办法将日期时间转换为特定格式?我附上一些屏幕截图供参考。
我使用的是第三方API,我不想透露这些方法。
Error response from the API method
现在我希望现在可以为DateTime变量指定格式。
答案 0 :(得分:1)
首先 - DateTime
没有一些格式。代表string
的{{1}}可以有格式。
要将DateTime
转换为特定格式为DateTime
,您可以使用ToString()
方法:
string
要解析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);
的{p> Convert.ToDateTime()
尝试使用您的CultureInfo
文化将string
转换为DateTime
。如果您想使用PC
,请使用接受Convert.ToDateTime()
和culture :: 的重载方法
string
答案 1 :(得分:0)
我使用ToString方法并为参数提供pattren。
例如: DateTime.Now.ToString(" DD-MM-YYYY&#34)