用Ruby格式化日期/时间到YYYY-MM-DD HH:MM:SS [复制]

问题描述 投票:0回答:3

这个问题在这里已有答案:

我想格式化Time.Now函数以显示YYYY-MM-DD HH:MM:SS而不是:“2018-03-09 09:47:19 +0000”该函数需要放在Time.Now函数中。

 require ‘roo’
 require ‘roo-xls’
 require ‘byebug’
 file_name = ARGV.first || “Template.xlsx”
 excel_file = Roo::Spreadsheet.open(“./#{file_name}“, extension: :xlsx)
 xml = Nokogiri::XML::Builder.new(encoding: ‘ISO-8859-15’) do |xml|
 xml.LIEFERUNG 

(“xmlns”:“http://testtest”,“xmlns:xsi”:“testtesttest”,“xsi:schemaLocation”:“testestest”,“version”:“1.0”,“erstellzeit”:“#{Time.now.strftime( “%F%H:%M:%S”)}“,”stufe“:”产品“)

 xml.ABSENDER do
 xml.KREDITGEBERNR “1206992”
 xml.Name “ALL”
 end
 xml.MELDUNGGROMIO(“erstellzeit”: “#{Time.now.strftime(“%F %H:%M:%S”)}“) do
 xml.MELDER do
 xml.KREDITGEBERNR “55093629”
 xml.Name “Finance”
 end
 File.open(“output.xml”, “w”) { |file| file.write(xml) }
ruby-on-rails ruby
3个回答
1
投票

您可以使用Time#strftime方法将时间格式化为各种不同的格式,包括您需要的格式。它需要一个参数来指定日期输出的格式。请查看documentation for this method以获取有关如何使用它的更多说明。

Time.now.strftime("%F %T")

%F指定我们希望YYYY-MM-DD格式的日期。接下来是一个空格,然后是%T说明符,它产生一个HH:MM:SS时间输出。

要将其合并到您的代码中:

"erstellzeit": "#{Time.now.strftime("%F %T")}"

或者,如果您要获得额外的+0000输出,请尝试:

"erstellzeit": "#{Time.now.strftime("%F %H:%M:%S")}"

0
投票

使用strftime

"erstellzeit": Time.now.strftime('%Y-%m-%d %H:%M:%S')


0
投票

strftime模块将完成工作。

Time.now.strftime("%Y-%m-%d %H:%M:%S")

# Details
%Y - Year with century (can be negative, 4 digits at least)
%m - Month of the year, zero-padded (01..12)
%d - Day of the month, zero-padded (01..31)

%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%M - Minute of the hour (00..59)
%S - Second of the minute (00..59)
© www.soinside.com 2019 - 2024. All rights reserved.