it-swarm.cn

如何以DD/MM/YYYY HH:MM格式获取当前日期/时间?

如何以DD/MM/YYYY HH:MM格式获取当前日期和时间并增加月份?

101
anonymous

格式化可以像这样完成(我假设你的意思是HH:MM而不是HH:SS,但它很容易改变):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

更新换班次数:

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"

这个顺便说一句你需要require 'date'

161
Michael Kohl
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"
22
Lars Haugseth
time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

对于增量减量月使用<< >>运算符

例子

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1
7
Fivell

日期:

#!/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

以上将显示,例如, 10/01/15

并且时间

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

以上将显示,例如, 11:33

然后把它放在一起,添加到最后:

puts date + " " + time
4
joe_young