How to split the string obtained from "Time.now" in ruby - ruby

A=Time.now
gives following output:
2012:05:18 12:20:50 +0530
I want to form a string like "May 18 , 2012". I tried changing A to string which was not possible. How can I achieve this?

Time.now.strftime('%b %e , %Y')
More info.

You can have a look at the Time Class, and method strftime.
It formats time according to the directives in the given format string.
http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime
For your current problem:
Time.now.strftime("%b %d, %Y")

Related

Changing the format from a mySQL datetime format to a different type in ruby?

I am attempting to change an SQL datetime variable (2016-06-09 14:29:34) into a format that looks like this (00:00_20160601). I have tried to follow a couple of SO questions that will allow me to format a Time object.
This is what I have done so far:
start_datetime = "2016-06-09 14:29:34"
t =Time.new(start_datetime)
t.strftime("%H:%M_%Y%d%m")
This results in the time being formatted to 2016-01-01 00:00:00 +0000, which is obviously not what I want. I was wondering if someone could help me format the datetime object the way I specified?
You can do this with DateTime:
require 'datetime'
DateTime.parse("2016-06-09 14:29:34").strftime("%H:%M_%Y%d%m")
#=> "14:29_20160906"
The format you're feeding in is basically ISO-8601 so it's parsed by default.
Feeding that value into Time.new is completely incorrect. The first argument there is the year, the rest have to be supplied separately. That's why you get 2016-01-01, since everything else comes out as defaults.
Time.new is converting automatically and the result of "2016-06-09 14:29:34".to_i is 2016.
It's not entirely clear why your day value changes from 09 in the input to 01 in the desired output, so I'll use the normal thing and output the same as was input:
require 'time'
start_datetime = "2016-06-09 14:29:34"
t = Time.strptime(start_datetime, '%Y-%m-%d %H:%M:%S')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"
Since the hours and minutes are being thrown away there are a couple of other ways to go about this.
Ignore the hours and minutes when parsing:
t = Time.strptime(start_datetime, '%Y-%m-%d')
Or use a Date object instead of a Time object:
require 'date'
start_datetime = "2016-06-09 14:29:34"
t = Date.strptime(start_datetime, '%Y-%m-%d')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"

What kind of date format is this and how do I transform it?

Making a GET request to a private (no public documentation) API returns data in JSON format.
The value for date looks as follows:
AanmeldDatum: "/Date(1262300400000+0100)/"
There's another variable called AangebodenSindsTekst which means OfferedSinceText and it's value is "8 augustus 2014". So the unknown Date format should get parsed into that specific value.
I'm wondering what kind of date format it is and how can I transform this to something like this 2014-08-08 with Ruby?
I've tried this:
require 'time'
t = '1262300400000+0100'
t2 = Time.parse(t)
# => ArgumentError: no time information in "1262300400000+0100"
Ruby's Time class is your friend, especially the strptime method:
require 'time'
foo = Time.strptime('1262300400000+0100', '%N') # => 2014-08-08 16:57:25 -0700
foo = Time.strptime('1262300400000+0100', '%N%z') # => 2014-08-08 08:57:25 -0700
%N tells Ruby to use nanoseconds. It's throwing away the precision after the 9th digit which is OK if you don't need the rest of the value. Nanosecond accuracy is good enough for most of us.
%z tells Ruby to find the timezone offset, which it then applies to the returned value.
While parse can often figure out how to tear apart an incoming string, it's not bullet-proof, nor is it all-knowing. For speed, I'd recommend learning and relying on strptime if your strings are consistent.
As the Tin Man pointed out in this answer, use the following instead:
Time.strptime('1262300400000+0100', '%Q%z')
it could be milliseconds since epoc, take off the last 3 zeros and plug it into a unix time stamp converter, comes out as Dec 31st 2009
TIME STAMP: 1262300400
DATE (M/D/Y # h:m:s): 12 / 31 / 09 # 11:00:00pm UTC

Ruby local_to_utc returns invalid year

I have the following date string ('US/Eastern'), which I need to convert to UTC:
date_src = '2014-07-07T23:10:00+0'
First I convert it to a "valid" format so I can operate it on later processes. I use the following to have an iso version of the date:
date = DateTime.parse(date_src).iso8601
At this point date is a nice '2014-07-07T23:10:00+00:00'. The last step on my process is to translate this date to UTC. I'm using the following:
TZInfo::Timezone.get('US/Eastern').local_to_utc(date)
The problem is this is giving me 20014 as output, instead of the UTC version of the original date. If I try:
TZInfo::Timezone.get('UTC').local_to_utc(date)
I get 2014, which is the correct year but still unexpected output.
Any ideas about what I'm doing wrong, and what I could use to solve the problem?
local_to_utc actually expects a Time or a DateTime instance:
TZInfo::Timezone.get('US/Eastern').local_to_utc(DateTime.parse(date_src))
# => #<DateTime: 2014-07-08T03:10:00+00:00 ((2456847j,11400s,0n),+0s,2299161j)>
From the documentation, you can have a hint on what actually happened:
All methods in TZInfo that operate on a time can be used with either Time or DateTime instances or with nteger timestamps (i.e. as returned by Time#to_i). The type of the values returned will match the the type passed in.
What actually happens is the local_to_utc calls to_i on the input parameter, which on a string returns the parsed integer from the beginning of the string (2014 in your case since date is the string 2014-07-07T23:10:00+00:00), and adds the time difference to it - 18000 for "US/Eastern" (5 hour difference), and 0 for UTC:
date.to_i
# => 2014
TZInfo::Timezone.get('US/Eastern').local_to_utc(date) - date.to_i
# => 18000
TZInfo::Timezone.get('UTC').local_to_utc(date) - date.to_i
# => 0
So the bottom line is - kind of serendipitously you saw this weird behavior, which stems from the compilation of some surprising quirks of the APIs you used...

How do I get day of the week from a date object?

I have a date object in Rails, which I'd like to format.
I've made it this far:
delivery_time.date.strftime("%w, %d/%m/%Y")
I'd like it to print out 'Wednesday, 04/01/2012'
Is there a quick method to change the '%w' into 'Wednesday'?
Looking at the Ruby docs for strftime
Time.now.strftime("%A, %d/%m/%Y")
=> "Wednesday, 04/01/2012"
The %A character is the full day name.
Date.today.strftime("%A")
=> "Wednesday"
Date.today.strftime("%A").downcase
=> "wednesday"
I know the OP wanted the string for the weekday, but if for whatever reason you are doing something more algorithmic and need a numerical representation, you can use cwday on the Date object
d = Date.new(2017,7,26)
d.cwday
#=> 3
Monday is 1
%A gives you day of the week.
strftime("%A, %d-%m-%Y") will give you:
Wednesday, 04-01-2012
Yes, you can use "%A" for the full day name.
See also http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html
try %A instead of %w
delivery_time.date.strftime("%A, %d/%m/%Y")

How do I format a date to mm/dd/yyyy in Ruby?

In Perl you can do:
my $current_time = DateTime->now();
my $mdy = $current_time->mdy("/");
What's the easiest way to do this in Ruby?
The strftime method can be used to format times:
Time.now.strftime("%m/%d/%Y")
I wrote a gem to help with formatting dates, and keeping your views DRY (not having to strftime every time you want to format dates).
Check it out at: http://github.com/platform45/easy_dates
You can simply use %D with strftime method
> Time.now.strftime("%D")
=> "11/24/14" # mm/dd/yy
my $current_time = DateTime->now();
my_current_time = DateTime.now
my $mdy = $current_time->mdy("/");
my_mdy = my_current_time.strftime("%m/%d/%Y")

Resources