Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - I need to convert string into a timestamp

I need to convert a string that represents a date to a timestamp object in Ruby.

For example:

   date_string = "18-Feb-2016 09:01:04"

   convert to a timestamp like so

   2016-02-18 14:01:04

I need to save this to a mysql database were the column is type timestamp.

I have researched this for most of the day and can not find a solution. I know you can use Time.parse but that includes timezone and DateTime.parse().to_time includes the timezone. Since it has to be a timestamp i can not use strftime method.

I need the time to be included because it will be used for calculation purposes.

Any help would be greatly appreciated.

Thank you

like image 677
Joe Avatar asked Jan 29 '26 05:01

Joe


2 Answers

TL;DR

datetime = DateTime.parse("18-Feb-2016 09:01:04").to_s(:db)

returns

"2016-02-18 09:01:04"

Here's a quick explanation...

1. Convert your string to a Date object with DateTime.parse

You can use the .parse method from the Date or DateTime class in order to parse a string. The parse method will return a Date object like this:

$ DateTime.parse("18-Feb-2016 09:01:04")
$ => #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>

.parse is a method provided by Ruby.

2. Format the string with DateTime.parse.to_s

Ruby on Rails gives you access to the DateTime.to_formatted_s method to change the formatting of the Date object prior to storing it in your database.

To match the format that you specified:

$ datetime = DateTime.parse("18-Feb-2016 09:01:04").to_formatted_s

Note: to_s is aliased from to_formatted_s and to_formatted_s is a method provided by Rails, not Ruby.

like image 65
Andrew Hendrie Avatar answered Jan 30 '26 17:01

Andrew Hendrie


Use to_datetime method in Rails.

"12-10-2015".to_datetime

=> Mon, 12 Oct 2015 10:36:00 +0000

http://apidock.com/rails/String/to_datetime

Edited to add precise answer.

like image 27
Albert Paul Avatar answered Jan 30 '26 18:01

Albert Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!