Ruby/Rails - DateTime parsing - ruby-on-rails

I'm trying to return a date as a string but remove the first 0 from the hour returned.
This is the code I'm using:
t = Time.new
current_date = Time.local(t.year, t.month, t.day, t.hour, t.min/30*30)
time_str = current_date.strftime("%I.%M+%p").downcase
puts time_str
Outputs:
03.00+pm
Expected output:
3.00+pm # need to remove the last zero from the hour(s)

just use %l instead of %I
.strftime("%l.%M+%p")

Just add one point: if you want to quickly find the format string, man date will give you the correct answer if you are on OS X or Linux.
If the strftime and date format string differs, you can always find it up in the Ruby document, here's the document for strftime.

Related

Cannot parse string to time with timezone offset included RFC3339 with seemingly contradictory errors

I am using Golang and time.Time to Parse a given string into a time object.
Using RFC3339 and time.Parse here is an example of my code:
t, err := time.Parse(time.RFC3339, "2020-08-08T00:22:44Z07:00")
if err != nil {
return nil, err
}
I get the follow errors.
When I include timezone offset I am getting:
ERRO[0002] parsing time "2020-08-08T00:22:44Z07:00": extra text: 07:00
When I don't include the timezone offset I am getting:
ERRO[0002] parsing time "2020-08-08T00:15:36" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "Z07:00"
How do I avoid this issue when parsing time into a structured object?
The presence of the character Z in the Go time.RFC3339 constant "2006-01-02T15:04:05Z07:00" does not mean that a date conforming to the pattern is supposed to include a Z followed by the time zone offset.
In fact, a date with Z followed by anything else is not a valid RFC3339 date. Hence, your first error extra text: 07:00
The Z stands for "Zulu Time", i.e. UTC time zone. From the RFC3339 specs:
Z A suffix which, when applied to a time, denotes a UTC
offset of 00:00; often spoken "Zulu" from the ICAO
phonetic alphabet representation of the letter "Z".
So the Z alone is already providing the time zone information, that is, UTC.
As #Flimzy noted in the comments, 2020-08-08T00:22:44Z would be a valid RFC3339 date.
t, err := time.Parse(time.RFC3339, "2020-08-08T00:22:44Z")
if err != nil {
panic(err)
}
fmt.Println(t) // 2020-08-08 00:22:44 +0000 UTC
Now, if you read the RFC3339 standard further, you see this definition:
time-zone = "Z" / time-numoffset
time-numoffset = ("+" / "-") time-hour [[":"] time-minute]
Which means that the time zone part of the date is either a Z or the offset. Clearly, since the Z already represents the offset 00:00, you can't have one more +/-HH:mm offset in the same date string.
But this also means that Z or the +/-HH:mm must be present. So if you remove both of them, you get your second error: cannot parse "" as "Z07:00"
The parser is attempting to read the "2020-08-08T00:15:36" string as RFC3339 so it expects either a Z or an offset after the seconds (or milliseconds, if any).
In conclusion, the Z07:00 in the Go time.RFC3339 pattern is just a representation of the fact that the date string is supposed to include a time zone. A valid RFC3339 date string must include either Z or the offset.

How to get local time as a formatted string in Lua

I need a date time string formatted as %Y-%m-%d %H:%M:%S.
I can't figure out how to use Lua's standard functions os.date() and os.time() to achieve that.
os.date is the function you are looking for. Its first optional parameter, format, does what you want:
os.date('%Y-%m-%d %H:%M:%S')
--> 2019-04-02 10:50:52
From the Lua 5.3 manual on os.date:
os.date ([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format.
If format starts with '!', then the date is formatted in Coordinated Universal Time.
If format is not "*t", then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.
You can learn more about the formatting rules of C's strftime here.
In case you don't get your local time for whatever reason you can simply add the required offset.
local timeShift = 3 * 60 * 60 -- +3 hours
os.date('%Y-%m-%d %H:%M:%S', os.time() + timeShift)
--> 2019-04-02 18:24:15 for 15:24:15 UTC
I use lib https://github.com/Tieske/date. Get localtime -
date(true):addminutes("your offset"):fmt('%Y-%m-%d %H:%M:%S'),

Converting server date with Z format to local nsdate

I need to convert this server date (Given from kinvey request) into local timezone.
I'm using the following code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss.sTZD"
print(dateFormatter.dateFromString(newValue))
The date format is this:
ect = "2016-08-28T16:30:06.553Z" or
lmt = "2016-08-28T16:30:06.553Z"
When I print the date it is nil, do you know what I'm doing wrong ?. I think it could be the end of the dateFormat
If your app can target only iOS7+, you can use format symbols described in:
Fixed Formats (in Data Formatting Guide)
Unicode Technical Standard #35 version tr35-31
second | S | 1..n | 3456 | Fractional Second - truncates (like other
time fields) to the count of letters. (example shows display using
pattern SSSS for seconds value 12.34567)
zone | X | 1 | -08,+0530,Z | The
ISO8601 basic format with hours field and optional minutes field. The
ISO8601 UTC indicator "Z" is used when local time offset is 0. (The
same as x, plus "Z".)
So, to parse fractional second, use uppercase 'S',
and 'X' for timezone including "Z" as UTC.
Try this:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
(I escaped 'T' as it may be used as another time formatting symbol in the future.)
PS. Though I couldn't have found a thread describing the date format which interprets "Z" as UTC+0000, ignoring or removing it may not be a bad solution, if some conditions met. Please find your best solution.

Convert HH:MM Time to Decimal before_save in Ruby on Rails

I have a duration field that is a decimal data type in my database.
My form accepts decimals (e.g. 1.5 hours) but I also want to be able to accept HH:MM (e.g. 1:30 for one hour and thirty minutes).
I'd like to be able to detect HH:MM with regex on before_save in my model and convert it to decimal so that users can enter either decimal or HH:MM. This part is fine and good, but the problem I'm having is testing the regex against the value in the field.
1:30 gets interpreted as data type --- !ruby/class 'BigDecimal' and I can't test it against regex.
Doing .to_s on it converts it to 1.0
How do I get my decimal-typed field to relax and let me convert its value to a string for regex testing in my model?
Here's my code:
# --- Model ---
before_save :convert_duration
def convert_duration
if duration =~ /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
time_pieces = duration.split(":")
hours = time_pieces[0].to_i
minutes = (time_pieces[1].to_f/60.0)
# Final value ready for database
self.duration = (hours+minutes).round(1)
end
end
Ruby 1.9.3; Rails 3.2.8
Use the duration_before_type_cast attribute when you want access to the original string.
Docs: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Accessing+attributes+before+they+have+been+typecasted

Python 3 - Parse time string with time offset

How can I parse a time string, such as Sun May 27 13:02:04 +0200 2012, to a tuple in UTC, using python3? The closest I can get is time.strptime(str, '%a %b %d %H:%M:%S %z %Y'), but it seems the offset is parsed but ignored. The above example is parsed to:
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=27, tm_hour=13, tm_min=1, tm_sec=35, tm_wday=6, tm_yday=148, tm_isdst=-1)
but I expected tm_hour=11.
Related: Convert string timestamp (with timezone offset) to local time. . ? python, Parsing time string in Python. Answers to both suggests the use of dateutil, but I'd prefer using the standard library, if possible.
tm_hour=11 would be incorrect. The time in the timestamp is 13:02:04, no matter what the offset is.
What you want to do is to convert that timestamp into a time in GMT, which the standard library won't do for you. So you will just have to extract the offset yourself (which is trivial) and then subtract it from the time.
I'd also recommend you to use the datetime library for this, date/time manipulation is much easier there, you can easily create a timedelta object from the offset and subtract that from the datetime object.

Resources