0

I need to reproduce the following Ruby code in Javascript but I can't find an equivalent for to_i.

beginning_of_last_full_hour = (Time.now.to_s.split(/:\d{2}/)[0] + ":00:00").to_time.to_i - 3600

Any help would be appreciated. I am trying to get the beginning of the last full hour. Thanks

asked Mar 19, 2015 at 12:26
1
  • to_i isn't really the important part. You need to convert a time object to a unix timestamp. Commented Mar 19, 2015 at 14:17

2 Answers 2

1

Javascript equivalent of Ruby to_i

parseInt().

Follow this for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Converting following code from Ruby to JavaScript:

(Time.now.to_s.split(/:\d{2}/)[0] + ":00:00").to_time.to_i
# => 1426788000
# Time.now # => 2015年03月19日 18:45:22 +0530

JS equivalent:

d = new Date();
new Date( d.toString().split(/:\d{2}/)[0] + ":00:00").getTime();
# 1426788000
answered Mar 19, 2015 at 12:28
Sign up to request clarification or add additional context in comments.

3 Comments

w3schools is frowned upon in these parts. You should change the link to developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
sure @Max will do that :)
thanks! still needed to divide 1000 like the next poster said for them to be the same
1

Seems like you want to take unix timestamp. In this case you should convert your Date object to it use:

date_object / 1000

or

date_object.getTime() / 1000

You should divide by 1000 because to_i for Ruby Time object return unix timestamp in seconds but getTime() return it in milliseconds.

answered Mar 19, 2015 at 12:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.