日期不转换为MM / dd / yyy

时间:2016-05-24 13:23:49

标签: c# date

我有一个平面文件,其中有一些日期以m / d / yy表示,有些日期为mm / dd / yy。我试图将它们全部转换为MM / dd / yy但没有成功。 代码如下。有人能告诉我我做错了什么。

;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 99999

; Maximum amount of time each script may spend parsing request data. Its a good
; idea to limit this time on productions servers in order to eliminate unexpectedly
; long running scripts.
; Note: This directive is hardcoded to -1 for the CLI SAPI
; Default Value: -1 (Unlimited)
; Development Value: 60 (60 seconds)
; Production Value: 60 (60 seconds)
; http://php.net/max-input-time
max_input_time = 4800

; Maximum input variable nesting level
; http://php.net/max-input-nesting-level
;max_input_nesting_level = 256

; How many GET/POST/COOKIE input variables may be accepted
; max_input_vars = 10000

; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit = 2048M

1 个答案:

答案 0 :(得分:3)

您只需添加第二个有效日期格式。它将尝试每一个,直到它成功。

StudentRec.birthdate = fields[i];
string[] format = { "MM/dd/yy", "M/d/yy" };  // Valid formats. 
DateTime dateValue;
if (StudentRec.birthdate.Length > 0)
{
    if (!DateTime.TryParseExact(StudentRec.birthdate, format,
                                new CultureInfo("en-US"),
                                DateTimeStyles.AllowWhiteSpaces , 
                                out dateValue))
    {  
        Console.WriteLine(StudentRec.birthdate);
        throw new MyException("Birthdate is not valid   ", o, strCNFileErr);
    }
}

注意:第一种有效的格式将返回。