Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby date time in string conversion to date time with milliseconds

Tags:

ruby

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>'
like image 689
Asha Singh Avatar asked Feb 15 '13 22:02

Asha Singh


People also ask

How do you convert Date to milliseconds?

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.

How do I change the Date format in Ruby?

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.

What is Strftime in Ruby?

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.


1 Answers

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"
like image 98
Michael Papile Avatar answered Sep 24 '22 03:09

Michael Papile