Parsing date like 1240915075 - ruby

I am learning programming and I choose Ruby as the first language to learn.
I am parsing an XML where dates are in this form: 1240915075 1224855068
How is this format called? How to use that value in a Date or Time object?
Thank you!

This is UNIX time (sometimes called Epoch time). It measures the number of seconds elapsed since January 1, 1970 (The Unix epoch is the time 00:00:00 UTC on 1 January 1970)
Here's an example converter: http://www.esqsoft.com/javascript_examples/date-to-epoch.htm
A stackoverflow question regarding converting integer time using Ruby: Ruby / Rails: convert int to time OR get time from integer?
use the Time.at function to convert e.g.:
t = Time.at(i)

That's Epoch Time (the first one corresponds to Tue Apr 28 2009 11:37:55 GMT+0100).
You can get a datetime out of it, using Time.at, like this:
Time.at(1240915075)

That is a unix timestamp - the number of seconds since jan 1st 1970.
An example of how to use it in Ruby is here:
t = Time.at(1215163257)
puts t.to_date
>> 2008-07-04

Related

Bot Composer UTC time recognition

Can someone explain why this IF statement is returning false if the current UTC time is 16:21 and the function is to return true if the current UTC time is >=09:00:00 && <=17:00:00
Have tried separate IF statements and extending the time bracket beyond reasonable doubt
Most likely because you're comparing a UTC time object to a string representation of the time. utcTime == string will not evaluate to true since a UTC time object and a string cannot be the same, and the UTC time converted to a string would not take the same format (as you can see when you printed the time.
The solution would be to instead create two UTC time objects with their values set to 09:00:00 and 17:00:00 respectively and comparing the current time to those instead.
= utcNow('HH:mm:ss') >= `09:00:00` && utcNow('HH:mm:ss') < `17:00:00`
Solution to question. Needed to enter time format similar to that of UTC format.

Conversion from epoch to datetime is incorrect

I've been using this answer to convert epoch time to DateTime. I have this epoch number:
epoch = 1549626705942
and do:
Time.at(epoch).to_datetime
However, I get this as the result:
#<DateTime: 51075-09-19T08:45:42+02:00 ((20376082j,24342s,0n),+7200s,2299161j)>
I'm using Ruby version 2.5.3p105 and my clock is set to the current year. This epoch value evaluates to today's date (February 2nd, 2019) yet I get a year 51075. Really not sure what's going on.
It's also weird because, when I enter my timestamp at a site like this one I get today's date but here I get the same result as my Ruby code.
Edit: I tried to remove the last 3 numbers of this date and got a correct date. So is it that there are 2 epoch "formats" so to say?
You are passing miliseconds to the Time::at() method. You should pass seconds there. Link to docs is here.
To retrieve Epoch value(in seconds), use Time#to_i
UPD
This will work for you:
Time.at(0, your_epoch_milliseconds, :millisecond)

Jmeter - get current date and time

I want to get the current date and time as example date: 11/10/2014 and time 8:30 am or 6:00 pm and pass it as parameters to my Jmeter test. Can some help me do this.
Use __time function:
${__time(dd/MM/yyyy,)}
${__time(hh:mm a,)}
Since JMeter 3.3, there are two new functions that let you compute a time:
__timeShift
"The timeShift function returns a date in the given format with the specified amount of seconds, minutes, hours, days or months added" and
__RandomDate
"The RandomDate function returns a random date that lies between the given start date and end date values."
Since JMeter 4.0:
dateTimeConvert
Convert a date or time from source to target format
If you're looking to learn jmeter correctly, this book will help you.
it seems to be the java SimpleDateFormat : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
here are some tests i did around 11:30pm on the 20th of May 2015
${__time(dd-mmm-yyyy HHmmss)} 20-032-2015 233224
${__time(d-MMM-yyyy hhmmss)} 20-May-2015 113224
${__time(dd-m-yyyy hhmmss)} 20-32-2015 113224
${__time(D-M-yyyy hhmmss)} 140-5-2015 113224
${__time(DD-MM-yyyy)} 140-05-2015
JMeter is using java SimpleDateFormat
For UTC with timezone use this
${__time(yyyy-MM-dd'T'hh:mm:ssX)}
Use ${__time(yyyy-MM-dd'T'hh:mm:ss)} to convert time into a particular timeformat.
Here are other formats that you can use:
yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
MM/dd/yy HH:mm:ss
You can use Z character to get milliseconds too.
For example:
yyyy/MM/dd HH:mm:ssZ => 2017-01-25T10:29:00-0700
yyyy/MM/dd HH:mm:ss.SSS'Z' => 2017-01-25T10:28:49.549Z
Most of the time yyyy/MM/dd HH:mm:ss.SSS'Z' is required in some APIs. It is better to know how to convert time into this format.
Actually, for UTC I used Z instead of X, e.g.
${__time(yyyy-MM-dd'T'hh:mm:ssZ)}
which gave me:
2017-09-14T09:24:54-0400
Use this format:
${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}
Which will give you:
2018-01-16T08:32:28.75Z
Should have double quotes surrounding the ${}
String todaysDate = "${__time(yyyy-MM-dd'T'HH:mm:ss.SSS'Z')}";

How to understand strptime vs. strftime

What's the difference between strptime and strftime? I see that strptime is a method in the DateTime class, and strftime is a method in the Time class.
What's the difference between Time and DateTime, other than that they have different core methods? The explanation for the Time class in the Ruby docs is helpful, but the one for DateTime just says "datetime". There's also the Date class, which says it provides Date and DateTime. Help me make sense of this.
I see strptime and I want to pronounce it "strip time", but that doesn't make sense. Is there a good mnemonic-device for it?
What do strptime and strftime mean, anyway?
How do you remember which does what?
The difference between Time and DateTime has to do with implementation. A large amount of the DateTime functionality comes from the Rails world and is an arbitrary date with time of day. It's more of a calendar-based system. Time is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.
In short, DateTime is what you get from a database in Rails where Time is what Ruby has traditionally used. If you're working with values where dates are important and you want to know things like the end of the month or what day it'll be six weeks ahead, use DateTime. If you're just measuring elapsed time and don't care about that, use Time. They're easy to convert between if necessary.
Date on the other hand is just a calendar date and doesn't have any associated times. You might want to use these where times are irrelevant.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification. I've rarely seen strptime used since DateTime.parse is usually good at picking up on what's going on, but if you really need to spell it out, by all means use the legacy parser.
strptime means string parser, this will convert a string format to datetime.
Example:-
datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")
datetime.datetime(2019, 8, 9, 1, 1, 1)//Result
strftime means string formatter, this will format a datetime object to string format.
Example:-
sample_date=datetime.strptime('2019-08-09 01:01:01', "%Y-%m-%d %H:%M:%S")
datetime.strftime(sample_date, "%Y-%d-%m %H:%M:%S")
'2019-09-08 01:01:01'//Result
I read the above answer and it is clear in its delineation of Time, DateTime and Date in Ruby.
Time is packaged with Ruby. It is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. More specifically, the Time class stores integer numbers, which presents the seconds intervals since the Epoch. We can think of this as Unix Time. It has some limitations. I read somewhere if stored as a 64-bit signed integer, it can represent dates between 1823-11-12 to 2116-02-20, but on my system it can represent dates outside this range. If you do not specify the timezone to use in the enviroment variable ENV['TZ'], then it will default to your system time found in /etc/localtime on Unix-like systems. When to use Time? It is useful for measuring time elapse or interpolating a timestamp into a string value.
Rails actually extends the Time class. It accomplishes this through ActiveSupport::TimeWithZone. It provides support for configurable time zones. Note Rails will always convert time zone to UTC before it writes to or reads from the database, no matter what time zone you set in the configuration file. In other words, it is the default behaviour of Rails that all your time will get saved into database in UTC format.
# Get current time using the time zone of current local system or ENV['TZ'] if the latter is set.
Time.now
# Get current time using the time zone of UTC
Time.now.utc
# Get the unix timestamp of current time => 1524855779
Time.now.to_i
# Convert from unix timestamp back to time form
Time.at(1524855779)
# USE Rails implementation of Time! Notice we say Time.current rather than Time.now. This will allow you to use the timezone defined in Rails configuration and get access to all the timezone goodies provided by ActiveSupport::TimeWithZone.
Time.current
TimeWithZone provides a lot of very useful helper methods:
# Get the time of n day, week, month, year ago
1.day.ago
1.week.ago
3.months.ago
1.year.ago
# Get the beginning of or end of the day, week, month ...
Time.now.beginning_of_day
30.days.ago.end_of_day
1.week.ago.end_of_month
# Convert time to unix timestamp
1.week.ago.beginning_of_day.to_i
# Convert time instance to date instance
1.month.ago.to_date
For most cases, the Time with the time zone class from Rails’ ActiveSupport is sufficient. But sometimes you just need a date.
Just as with the Time class, Ruby is packaged with the Date class. Simply require the time library:
require "time"
Time.parse("Dec 8 2015 10:19")
#=> 2015-12-08 10:19:00 -0200
Date.parse("Dec 8 2015")
#=> #<Date: 2015-12-08>
Time.new(2015, 12, 8, 10, 19)
#=> 2015-12-08 10:19:00 -0200
Date.new(2015, 12, 8)
Since Date is part of Ruby, it by default uses the timezone defined in /etc/localtime on Unix-like systems, unless you modify the TZ environmental variable. Just as with the Time class, Rails extends the Date class. Use Date.current instead of Date.today to take advantage of ActiveSupport::TimeWithZone and use Rails-based timezone configurations.
Now there is one more class available with regards to dates and times. DateTime is a subclass of Date and can easily handles date, hour, minute, second and offset. It is both available in Ruby (via require 'time') and in Rails (via require 'date'). Rails extends it with TimeZone capabilities just like with the Time class.
require 'date'
DateTime.new(2001,2,3,4,5,6)
I personally do not see a need for using DateTime in your applications, for you can use Time itself to represent dates and times, and you can use Date to represent dates.
The second part of the question was regarding strptime and strftime. Time, Date and DateTime all have the strptime and strftime methods. strptime parses the given string representation and creates an object. Here is an example:
> result = Time.strptime "04/27/2018", "%m/%d/%Y"
=> 2018-04-27 00:00:00 -0400
> result.class
=> Time
This is useful if you have an application and a user submits a form and you are given a date and/or represented as a string. You will want to parse it into a Time or Date before you save it to the database.
strftime formats a date or time. So you call it on a Date or Time object:
> Date.current.strftime("%Y-%m-%d")
=> "2018-04-27"
And you can use them together to first parse user input and then format it in a certain way, perhaps to output into a csv file:
value = Date.strptime(val, '%m/%d/%Y').strftime('%Y-%m-%d')

Is Date.today in UTC?

Calling Date.today in Ruby returns the current date. However, what timezone is it in? I assume UTC, but I want to make sure. The documentation doesn't state either way.
You can get away by using
Time.now.utc.to_date
in ruby
TL;DR: Date.today uses the system’s local time zone. If you require it be in UTC, instead get the date from a UTC time, e.g. Time.now.utc.to_date.
Dates do not have timezones, since they don't represent a time.
That said, as for how it calculates the current day, let's look at this extract from the code for Date.today:
time_t t;
struct tm tm;
// ...
if (time(&t) == -1)
rb_sys_fail("time");
if (!localtime_r(&t, &tm))
rb_sys_fail("localtime");
It then proceeds to use use tm to create the Date object. Since tm contains the system's local time using localtime(), Date.today therefore uses the system's local time, not UTC.
You can always use Time#utc on any Time convert it in-place to UTC, or Time#getutc to return a new equivalent Time object in UTC. You could then call Time#to_date on that to get a Date. So: some_time.getutc.to_date.
If you’re using ActiveSupport’s time zone support (included with Rails), note that it is completely separate from Ruby’s time constructors and does not affect them (i.e. it does not change how Time.now or Date.today work). See also ActiveSupport extensions to Time.
An instance of Date is represented as an Astronomical Julian Day Number; it has no fractional part of a day. While a Julian Day is relative to GMT - so technically an instance of Date should be considered to be in GMT - for most purposes you can ignore that and treat it as having no timezone. You would only care about a time zone if you converted it to a DateTime or Time.
ActiveSupport's tools for date conversion let you specify whether you want local time or UTC.
E.g.:
>> t = Date.today.to_time
=> Wed Apr 18 00:00:00 -0400 2012
>> t.zone
=> "EDT"
>> t = Date.today.to_time(:utc)
=> Wed Apr 18 00:00:00 UTC 2012
>> t.zone
=> "UTC"
You can use
Date.current
To get the current date on the configured timezone.
If your rails applications is configured to run in time zone UTC then just use Time.zone.today, otherwise force it by using Time.now.utc.to_date
Ruby
# Using local timezone
Date.today
Ruby on Rails
# Using UTC
Date.yesterday
Date.current
Date.tomorrow
This is specifically nasty because when using e.g. Date.today and Date.yesterday in conjunction, it might produce quite unexpected results depending on the timezone and the current time.
For example, at 00:30 in timezone CET (UTC+1) Date.yesterday will be two days before Date.today. In other cases, Date.today and Date.yesterday can have the same value.

Resources