简体   繁体   中英

how to parse a date with strptime when zone is optional

I have datetime string in the format "1/4/2013 3:39:41 PM" and I am using the following code DateTime.strptime(s, '%d/%m/%Y %H:%M:%S %p') and it works.

But the problem is when the time is in AM, the input string does not have 'AM' present. So the string is like "1/4/2013 3:39:41" when referring to AM. And in these cases my code for parsing date throws error

ArgumentError: invalid date
    from (irb):45:in `strptime'

How can I make the %p optional in my template?

thanks

Not the best solution, but you can continue:

if s.split(' ').size == 3
   format = '%d/%m/%Y %H:%M:%S %p'
// you can implement further variations here...    
else 
   format = '%d/%m/%Y %H:%M:%S %p'

DateTime.strptime(s, format)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM