【问题标题】:How to convert string to date "141104" with 2014 year?如何将字符串转换为 2014 年的日期“141104”?
【发布时间】:2015-01-06 07:38:07
【问题描述】:

我有字符串,想转换成日期。

问题是当转换时(例如)"141104" ==> 它将是"04/11/0014" 我将如何解决年份0014 成为2014?

我用过:

DateTime EntranceDeclaratioDate = new DateTime(int.Parse(outputDueNo.ThirdPart.Substring(0, 2)), int.Parse(outputDueNo.ThirdPart.Substring(2, 2)), int.Parse(outputDueNo.ThirdPart.Substring(4, 2)));

【问题讨论】:

标签: c# string datetime


【解决方案1】:

因为DateTime(Int32, Int32, Int32) constructor 将exact 年作为第一个参数。不是两位数的表示。

这就是为什么你的代码相当于

new DateTime(14, 11, 04);

不是

new DateTime(2014, 11, 04);

通常,拆分字符串并在DateTime 构造函数中使用这些部分并不是一个好主意。至少我不喜欢。

如果yyMMdd 不是您文化的标准日期和时间格式,您可以使用自定义日期和时间格式解析;

string s = "141104";
DateTime EntranceDeclaratioDate;
if(DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture,
                          DateTimeStyles.None,
                          out EntranceDeclaratioDate))
{
    // Successfull parsing, now EntranceDeclaratioDate is 04/11/2014 00:00:00
}

The "yy" specifier 将年份表示为两位数。此说明符基于您当前日历的Calendar.TwoDigitYearMax property,在我的示例中为Gregorian Calendar,因为我使用InvariantCulture 作为IFormatProvider。

【讨论】:

    【解决方案2】:

    使用您的方法,可以通过以下添加来更正年份。

     DateTime EntranceDeclaratioDate
       = new DateTime(int.Parse(outputDueNo.ThirdPart.Substring(0, 2)) + 2000,
                      int.Parse(outputDueNo.ThirdPart.Substring(2, 2)),
                      int.Parse(outputDueNo.ThirdPart.Substring(4, 2)));
    

    但是,我强烈支持上述评论并建议使用DateTime.Parse 方法。

    【讨论】:

    • 这个字符串没有起始索引为18。
    • 是的,我知道这一点,但在原始问题中使用了相同的索引。
    • 不,它不起作用。使用你的方法,你如何表达 1914 年?
    【解决方案3】:
    string outputDueNo = "141104";
    char[] st = new char[6];
    st=outputDueNo.ToCharArray();
    
    string date = st[4].ToString() + st[5].ToString() + "/" + st[2].ToString() + st[3].ToString() + "/" + "20" + st[0].ToString() + st[1].ToString();      
    DateTime ds = Convert.ToDateTime(date);
    

    【讨论】:

    • 您的char 数组完全没有必要。您可以将一个字符声明为st[4],而无需创建此st 数组。并且不能保证 OP 的 CurrentCulture 解析您的 date 字符串。抱歉,这是解决此问题的不好方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多