2014-05-22 241 views
-1

这里我想将日期转换为使用tostring的字符串,但是当我将其转换回来时(字符串转换为日期时间),格式不同。如何将字符串转换为datetime(datetime)格式相同?

static void Main(string[] args) 
    { 
     string cc = "2014/12/2"; 
     DateTime dt = DateTime.Parse(cc); 
     Console.WriteLine(dt); 
     Console.ReadLine(); 
    } 

预期输出: 2014年12月2日 但我得到: 2014年12月2日

+0

有什么不对当前的代码中使用日期模式? –

+0

它显示12/2/2014,但我想在2014/12/2 – stpdevi

+1

日期以默认格式显示,除非您明确使用tostring格式化它。许多答案是正确的,但你说这不是你想要的。要么你的问题很不清楚,要么你不明白你问的是什么。 –

回答

1
string DateString = "06/20/1990"; 
IFormatProvider culture = new CultureInfo("en-US", true); 
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture); 

这将是你的愿望输出

udpated

string DateString = "20/06/1990";; 
       IFormatProvider culture = new CultureInfo("en-US", true); 
       DateTime dt = DateTime.ParseExact(DateString,"dd/mm/yyyy",culture); 
       dt.ToString("yyyy-MM-dd"); 
+0

嗨它显示错误:字符串未被识别为有效的日期时间。 – stpdevi

+0

@stpdevi你在传递什么? –

+0

没有任何我已经执行的代码,因为它是,但它显示以上错误 – stpdevi

1

呼叫ToString所提供的格式,当您转换DateTime实例回string

Console.WriteLine(dt.ToString(@"yyyy/M/d"); 
+0

sry我想反向转换为datetime格式如下yyyy/M/dd – stpdevi

+0

I想要使用日期时间不tostring转换 – stpdevi

1

试试这个

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
           CultureInfo.InvariantCulture); 
dt.ToString("yyyyMMdd"); 
1

使用本:

string cc = "2014/12/2"; 
    DateTime dt = DateTime.Parse(cc); 
    string str = dt.ToString("yyyy/M/dd"); // 2014/12/02 as you wanted 
    Console.WriteLine(str); 
    Console.ReadLine(); 
1

可以使用

string formattedDate= dt.ToString("yyyy/M/d"); 

对于反向您可以使用

DateTime newDate = DateTime.ParseExact("2014/05/22", "yyyy/M/d", null); 

所以,如果你期望的输出是这样的:2014年12月2日 你必须使用

newDate.ToString( “YYYY/M/d”) ;

+0

sry我想反向转换为datetime与以下格式yyyy/M/dd – stpdevi

+0

请检查编辑 –

+0

sry它给予12.2.2014输出 – stpdevi

1

正如你可以阅读hereDateTime.ToString()使用CurrentCulture来决定如何输出(CultureInfoCurrentCulture在C提供了有关如何格式化日期,货币信息,日历等,这被称为区域 ++)格式。

因此,如以前的答案建议的simlplest溶液,是使用的ToString()过载它接受一个格式字符串,有效地重写CurrentCulture信息:

dt.ToString(@"yyyy/MM/dd"); 

更多关于日期时间格式可以发现here

+0

我的问题是在我的dbd数据类型是datetime所以我应该添加相同的格式而不转换为tostring – stpdevi

+0

@stpdevi - 在引擎盖下,'Console.WriteLine(dt)'调用默认'dt.ToString )'。它对任何非字符串参数都这样做。 – bavaza

1

这很简单,你只需要显示

string cc = "2014/12/2"; 
string datePatt = @"yyyy/MM/d"; 
DateTime dt = Convert.ToDateTime(cc); 
Console.WriteLine(dt.ToString(datePatt));