这个日期字符串有什么问题?导致:“未处理的异常:System.FormatException”

时间:2011-02-11 16:54:05

标签: datetime f#

我这样称呼我的剧本:

>Driver.exe 26268 "01-01-2011" "02-01-2011"

arg 0 : c:\Services\JasperBatchService\Release\JasperBatchDriver.exe
arg 1 : 26268

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi,  DateTimeStyles style)
   at Program.main(String[] args) in C:\sswork\dev\fSharpServices\ops-Projects\JasperBatchDriver\Program.fs:line 65

这是相关代码:

let mutable argNum = 0
let cmdArgs = System.Environment.GetCommandLineArgs()    

for arg in cmdArgs do
    match argNum with
    | 1 -> pmID      <- System.Int32.Parse arg 
    | 2 -> startDate <- DateTime.ParseExact(arg, "D", new CultureInfo("en-US"))
    | 3 -> endDate   <- DateTime.ParseExact(arg, "D", new CultureInfo("en-US"))
    | _ -> ()
    printfn "arg %d : %s" argNum arg
    argNum <- argNum + 1

我也试过这个:

for arg in cmdArgs do
    match argNum with
    | 1 -> pmID      <- System.Int32.Parse arg 
    | 2 -> startDate <- DateTime.ParseExact(arg, "MM-dd-yyyy", new CultureInfo("en-US"))
    | 3 -> endDate   <- DateTime.ParseExact(arg, "MM-dd-yyyy", new CultureInfo("en-US"))
    | _ -> ()
    printfn "arg %d : %s" argNum arg
    argNum <- argNum + 1

和此:

for arg in cmdArgs do
    match argNum with
    | 1 -> pmID      <- System.Int32.Parse arg 
    | 2 -> startDate <- DateTime.ParseExact(arg, "MM/dd/yyyy", new CultureInfo("en-US"))
    | 3 -> endDate   <- DateTime.ParseExact(arg, "MM/dd/yyyy", new CultureInfo("en-US"))
    | _ -> ()
    printfn "arg %d : %s" argNum arg
    argNum <- argNum + 1

我似乎最接近的是使用这个:

(startDate).ToString("MM/dd/yyyy")

但是这会在输出中添加双引号....

3 个答案:

答案 0 :(得分:4)

看起来你对DateTime.ParseExact的调用期望“D”(长日期模式)格式,这与你提供的格式不同。如果您计划接受MM-DD-YYYY格式的参数,则需要使用自定义格式。

试试这个:

DateTime.ParseExact(arg, "MM-dd-yyyy", new CultureInfo("en-US"))

答案 1 :(得分:1)

这有效(来自fsi):

System.DateTime.ParseExact ("01-01-2011", "MM-dd-yyyy",
System.Globalization.CultureInfo "en-US");;
val it : System.DateTime = 1/1/2011 12:00:00 AM {Date = 1/1/2011 12:00:00 AM;
                                             Day = 1;
                                             DayOfWeek = Saturday;
                                             DayOfYear = 1;
                                             Hour = 0;
                                             Kind = Unspecified;
                                             Millisecond = 0;
                                             Minute = 0;
                                             Month = 1;
                                             Second = 0;
                                             Ticks = 634294368000000000L;
                                             TimeOfDay = 00:00:00;
                                             Year = 2011;}

你是如何迭代args数组的?是不是可变的argNum总是0?

答案 2 :(得分:0)

arg 2应采用此格式01-01-2011