从命令行获取特定时间不起作用

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

我有一个计算很多东西的程序。虽然我通过ruby code.rb运行代码,但一切都还可以。问题开始时,我想通过命令行运行它带有附加选项:ruby code.rb --time 201712121100。

有问题的代码如下:

include Options #here I have some options to choose, like --time

def calculate_p(time, mode)
   if mode
      calculator = calc1
   else
      calculator = calc2
   end
   calculate_t(time, calculator)
 end

def calculate_t(time, calculator)
   date_ymd = time.strftime("%Y%m%d")
   time_hm  = time.strftime("%H%M")

   calculator
     .with(date_ymd, time_hm)
   .run do |result|
      if result.ok?
         result.stdout.pop.split.first
      else
        msgw("Program returned with errors.", :error)
        msgw("stdout: %s; stderr: %s" % [result.stdout, result.stderr], :error)
        false
      end
    end
 end

time  = Options.get('--time')
           .andand do |time_op|
              msgw('Taking time from command line arguments') do
                time_op.pop.andand
              end
            end || msgw('Calculating time for now.') do
              Time.now.utc
            end || abort
calc=calculate_p(time, mode)

msgw只是定义打印消息。

mode采用truefalse值。

我收到一个错误:

calculate_t:未定义的方法strftime"201712121100":StringNoMethodError)”

我究竟做错了什么?为什么使用Time.now.utc工作,而给出一个特定的时间不是?

我还从这里检查了解决方案Rails undefined method `strftime' for "2013-03-06":String和Date.parse()给出了同样的错误。

ruby strftime
1个回答
2
投票

问题在于:

time_op.pop.andand

从命令行获取的time_op是一个字符串,你需要一个Time实例。得到它,使用DateTime#strptime

DateTime.strptime(time_op.pop, "%Y%m%d%H%M").to_time.andand
© www.soinside.com 2019 - 2024. All rights reserved.