Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string containing date and time in a custom format

I have a string of the next format "ORDER20100322194007", where 20100322 is a date and 194007 is a time. How to parse a string and get the contained DateTime object?

like image 457
akrisanov Avatar asked Apr 01 '10 13:04

akrisanov


People also ask

How do you parse a string to a date?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

How do I convert a DateTime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

How do I parse a date format from a string in Python?

parse() can be used to convert a string into date-time format. The only parameter used is the string.

What is date/time parse?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.


2 Answers

Will it always start with ORDER?

string pattern = "'ORDER'yyyyMMddHHmmss"; DateTime dt; if (DateTime.TryParseExact(text, pattern, CultureInfo.InvariantCulture,                             DateTimeStyles.None,                            out dt)) {     // dt is the parsed value }  else  {     // Invalid string } 

If the string being invalid should throw an exception, then use DateTime.ParseExact instead of DateTime.TryParseExact

If it doesn't always begin with "ORDER" then do whatever you need to in order to get just the date and time part, and remove "'ORDER'" from the format pattern above.

like image 131
Jon Skeet Avatar answered Sep 17 '22 17:09

Jon Skeet


You can use DateTime.ParseExact method to specify the format that should be used while parsing.

like image 30
Giorgi Avatar answered Sep 18 '22 17:09

Giorgi