NameError: undefined method ‘parse’ for class ‘NilClass’ when doing Time.zone.parse

If you get following error when trying to parse time:

Time.zone.parse('2019-01-01 11:11:11')

Traceback (most recent call last):
16: from /bundler/friendly_errors.rb:124:in `with_friendly_errors'
15: from /bundle:30:in `block in '
14: from /bundler/cli.rb:18:in `start'
13: from /bundler/vendor/thor/lib/thor/base.rb:466:in `start'
12: from /bundler/cli.rb:27:in `dispatch'
11: from /bundler/vendor/thor/lib/thor.rb:387:in `dispatch'
10: from /bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
9: from /bundler/vendor/thor/lib/thor/command.rb:27:in `run'
8: from /bundler/cli.rb:465:in `exec'
7: from /bundler/cli/exec.rb:28:in `run'
6: from /bundler/cli/exec.rb:74:in `kernel_load'
5: from /bundler/cli/exec.rb:74:in `load'
4: from bin/irb:23:in `'
3: from bin/irb:23:in `load'
2: from lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `'
1: from (irb):5

NoMethodError (undefined method `parse' for nil:NilClass)

it means you’ve forgotten to set the timezone:

Time.zone = 'UTC'

Also, keep in mind, that each time you spin up a new thread, it won’t have a timezone defined (outside of Rails):

Time.zone = 'UTC'

Time.zone.parse('2019-01-01 11:11:11') # works

Thread.abort_on_exception = true

# fails
Thread.new do
  Time.zone.parse('2019-01-01 11:11:11')
end

# NoMethodError: undefined method `parse' for nil:NilClass

In order to fix that, you need to set the time zone in each of your newly created threads:

Time.zone = 'UTC'

Time.zone.parse('2019-01-01 11:11:11') # works

Thread.abort_on_exception = true

# works
Thread.new do
  Time.zone = 'UTC'
  Time.zone.parse('2019-01-01 11:11:11')
end

Cover photo by Alex The Shutter on Attribution-NonCommercial 2.0 Generic (CC BY-NC 2.0) license.

The post NameError: undefined method ‘parse’ for class ‘NilClass’ when doing Time.zone.parse appeared first on Running with Ruby.

Ubuntu Server Admin

Recent Posts

Shoryuken Has a New Maintainer, and v7.0.0 Is Almost There

After a decade under Pablo Cantero's stewardship, Shoryuken has a new maintainer - me. I'm…

4 days ago

A better way to provision NVIDIA BlueField DPUs at scale with MAAS

MAAS 3.7 has been officially released and it includes a bunch of cool new features.…

2 weeks ago

Ruby Floats: When 2.6x Faster Is Actually Slower (and Then Faster Again)

Update: This article originally concluded that Eisel-Lemire wasn't worth it for Ruby. I was wrong.…

2 weeks ago

MicroCeph: why it’s the superior MinIO alternative (and how to use it)

Recently, the team at MinIO moved the open source project into maintenance mode and will…

2 weeks ago

MicroCeph: why it’s the superior MinIO alternative (and how to use it)

Recently, the team at MinIO moved the open source project into maintenance mode and will…

2 weeks ago

Design and Documentation clinics at FOSDEM Fringe 2026

FOSDEM is one of the biggest and most exciting open source events of the year,…

2 weeks ago