如何将字符串值转换为日期格式

时间:2013-12-30 13:16:07

标签: c#

string strDateFrom;
string strDateTo;

CrystalDecisions.Shared.ParameterDiscreteValue DateValue = new CrystalDecisions.Shared.ParameterDiscreteValue();

if ((strDateFrom != "") && (strDateTo != ""))      
{                                      
    DateValue.Value = "(From: " + strDateFrom + " - " + strDateTo + ")";
}     
else     
{
    DateValue.Value = "(ALL DATES)";    
}

3 个答案:

答案 0 :(得分:0)

您可以使用DateTime.Parse

string date = "2020-02-02";
    DateTime time = DateTime.Parse(date);
    Console.WriteLine(time);

use

DateTime oDate = DateTime.Parse(string s);

答案 1 :(得分:0)

为避免格式化问题,我更喜欢使用DateTime.ParseExactDateTime.TryParseExact

这些方法和DateTime.Parse之间的区别主要是天气,你知道字符串的日期格式(然后你使用DateTime.ParseExact)或不使用DateTime.Parse)。

您可以详细了解ParseExactTryParseExact

修改: 来自链接的示例代码:

 string dateString, format;  
      DateTime result;
      CultureInfo provider = CultureInfo.InvariantCulture;

      // Parse date-only value with invariant culture.
      dateString = "06/15/2008";
      format = "d";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      } 

      // Parse date-only value without leading zero in month using "d" format.
      // Should throw a FormatException because standard short date pattern of  
      // invariant culture requires two-digit month.
      dateString = "6/15/2008";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

答案 2 :(得分:0)

如果知道使用的格式,您可以尝试DateTime.ParseExact()DateTime.TryParseExact()

  String text = "30/12/2013"; 

  DateTime result = DateTime.ParseExact(text, "d/M/yyyy", CultureInfo.InvariantCulture);