How do I get the current Date/time in DD/MM/YYYY HH:MM format?
How can I get the current date and time in DD/MM/YYYY HH:MM
format and also increment the month?
Solution 1:
The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):
Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"
Updated for the shifting:
d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"
You need to require 'date'
for this btw.
Solution 2:
require 'date'
current_time = DateTime.now
current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"
current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"
Solution 3:
time = Time.now.to_s
time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")
for increment decrement month use << >> operators
examples
datetime_month_before = DateTime.parse(time) << 1
datetime_month_before = DateTime.now << 1
Solution 4:
For date:
#!/usr/bin/ruby -w
date = Time.new
#set 'date' equal to the current date/time.
date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY
puts date
#output the date
The above will display, for example, 10/01/15
And for time
time = Time.new
#set 'time' equal to the current time.
time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and minute
puts time
#output the time
The above will display, for example, 11:33
Then to put it together, add to the end:
puts date + " " + time