This is a Ruby question (1.9.1)
I have the following date and time in a string:
29 Sep 2013 12:25:00.367
I first want to convert it from string to date and time and then add 10 seconds to it and convert it back to the same string format as above.
I wrote this code:
format = "%d %b %Y %H:%M:%S"
date_time = "29 Sep 2013 22:11:30.195"
parsed_time = DateTime.strptime(date_time, format)
puts " new date time is #{parsed_time}"
Which outputs:
new date time is 2013-09-29T22:11:30+00:00
I did not see "195". I tried format = "%d %b %Y %H:%M:%S.%3N"
and this gives:
fileOpTest:34:in `strptime': invalid date (ArgumentError) from fileOpTest:34:in `<main>'
This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.
You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
Ruby | Time strftime() function Time#strftime() is a Time class method which returns the time format according to the directives in the given format string. Syntax: Time.strftime() Parameter: Time values. Return: time format according to the directives in the given format string.
This can be done very easily using the Time class. You can add to a Time by adding seconds. Then use #strftime
t= Time.parse('29 Sep 2013 12:25:00.367')
=> 2013-09-29 12:25:00 -0400
t=t + 10
=> 2013-09-29 12:25:10 -0400
t.strftime("%d %b %Y %H:%M:%S.%3N")
=> "29 Sep 2013 12:25:10.367"
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