if I get a string from the command line and it looks like this:
'1-1-2011'
how can I convert that string to a DateTime object in F#?
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.
Use ParseExact to Convert String to DateTime in PowerShell The ParseExact method helps convert the specified date and time string to the DateTime data type. We have a variable $date , which contains the date in string format. You can check the data type using the GetType() method.
To add one nice thing to what 7sharp9 wrote, if you also want to handle failures, you can write:
match System.DateTime.TryParse "1-1-2011" with
| true, date -> printfn "Success: %A" date
| false, _ -> printfn "Failed!"
This is not obvious, because the TryParse
method has a byref<DateTime>
as the last argument (and it is used using out
in C#), but F# allows you to call the method like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With