Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to System.DateTime in F#

Tags:

date

f#

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#?

like image 489
Ramy Avatar asked Feb 09 '11 20:02

Ramy


People also ask

How do I convert a string to a datetime in Python?

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.

How do I convert a string to a timestamp in python?

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.

How do I convert a string to a date in PowerShell?

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.


1 Answers

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.

like image 85
Tomas Petricek Avatar answered Oct 29 '22 17:10

Tomas Petricek