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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7415982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:19:45  来源:igfitidea点击:

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

ruby

提问by anonymous

How can I get the current date and time in DD/MM/YYYY HH:MMformat and also increment the month?

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

回答by Michael Kohl

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

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

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.

你需要require 'date'为此顺便说一句。

回答by Lars Haugseth

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"

回答by Fivell

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

回答by joe_young

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

上面会显示,例如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

上面会显示,例如11:33

Then to put it together, add to the end:

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

puts date + " " + time