C#-转换DateTime格式yyyy-MM-dd [英] C# - Convert DateTime format yyyy-MM-dd
问题描述
我正在尝试将DateTime格式从"dd/MM/yyyy"更改为"yyyy-MM-dd"
I am trying to change the DateTime format from "dd/MM/yyyy" to "yyyy-MM-dd"
这是我目前所拥有的:
DateTime date = Convert.ToDateTime("31/01/2000");
Console.WriteLine(date);
String format = "yyyy-MM-dd";
String dateStr = date.ToString(format);
Console.WriteLine(dateStr);
DateTime parsedDate = DateTime.ParseExact(dateStr, format, CultureInfo.InvariantCulture);
Console.WriteLine(parsedDate);
我得到这些结果:
31/01/2000 12:00:00 AM
2000-01-31
31/01/2000 12:00:00 AM
最终,我希望最后一个结果是2000-01-31
Ultimately, I want the last result to be 2000-01-31
只是为了阐明我的实际目标.我正在使用SSIS将DT_DATE(dd/MM/yyyy)字段转换为另一个DT_DATE(yyyy-MM-dd)字段.所以以为我会使用脚本组件.这意味着我无法将其转换回字符串.
Just to clarify my actual objective. I am using SSIS to convert a DT_DATE(dd/MM/yyyy) field into another DT_DATE(yyyy-MM-dd) field. So thought I would use a Script Component. This means I can't convert it back into a String.
EDIT ++ answer:
EDIT++answer:
对不起,每个人,我想我已经把这个问题弄糊涂了,但是我现在可以自己回答.
Sorry everyone, I think I've muddled up the question, but I can answer it myself now.
我的目标是在SSIS中将源字段DT_DATE(dd/MM/yyyy)转换为目标字段DT_DATE(yyyy-MM-dd).
My goal was to convert source field DT_DATE(dd/MM/yyyy) into dest field DT_DATE(yyyy-MM-dd) in SSIS.
我首先尝试通过(DT_DBDATE)字段替换原始字段"来使用派生列.这没有用,因为它给了我原始来源.
I first tried using a Derived Column by 'Replacing the original field' with (DT_DBDATE)field. This didn't work as it gave me the original source.
因此,我尝试使用一个脚本组件,该脚本组件导致了我的问题的顶部,并且引起了很多困惑.根本没用.
So I tried using a Script Component which led to the top part of my question, and lots of confusion. It simply didn't work.
解决方案是通过添加新列"并为其指定(DT_DBDATE)字段来使用派生列.DT_DBDATE的原始格式实际上是yyyy-MM-dd.
The solution was to use a Derived Column by 'Adding a new column' and giving it (DT_DBDATE)field. DT_DBDATE's original format is in fact yyyy-MM-dd.
推荐答案
我认为您只需要了解ToString重载:
I think you just need to know about the ToString overloads:
string fromFormat = "dd/MM/yyyy";
string toFormat = "yyyy-MM-dd";
DateTime newDate = DateTime.ParseExact("15/01/2001", fromFormat, null);
Console.WriteLine(newDate.ToString(toFormat));
这篇关于C#-转换DateTime格式yyyy-MM-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!