繁体   English   中英

在Ruby中将字符串转换为Date

[英]Converting a string to Date in Ruby

我试图使用Date.strptimedd/mm/yyyy格式的字符串26/03/2012解析为Ruby的Date,如下所示:

#!/usr/bin/ruby
require 'date'
puts 'Ruby Version: ' + RUBY_VERSION
date_str = '26/03/2012'

date = Date.strptime(date_str, "%d/%m/%y")
puts 'Parsed Date: ' + date.to_s

输出为:

Ruby Version: 1.8.7
Parsed Date: 2020-03-26

年部分已变成2020 ,而不是2012

那应该是%Y大写,而不是%y

date = Date.strptime(date_str, "%d/%m/%Y")
puts 'Parsed Date: ' + date.to_s
# Parsed Date: 2012-03-26

从文档:

 Date (Year, Month, Day):
    %Y - Year with century (can be negative, 4 digits at least)
            -0001, 0000, 1995, 2009, 14292, etc.
    %C - year / 100 (round down.  20 in 2009)
    %y - year % 100 (00..99)

由于%y仅期望两位数,因此它采用前两位20并假定是2020两位数表示,因为2020 % 100 = 20

如果将strptime函数更改为date = Date.striptime(date_str, "%d/%m/%Y")

它将正确输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM