Question

I have a date/time format:

format = '%Y年%b%d日 %H:%M'

calling Time#strftime(format) (e.g. Time.now.strftime(format) produces:

> Time.now.strftime(format)
=> "2013?Jun20? 11:56"

I'm using jruby 1.7.2 (1.9.3p327) on Windows. Is there a way to make strftime Unicode-compatible?

Update

Windows console hasn't been very accommodating for Unicode, when I output just format, I get:

> I18n.t :'time.formats.long'
=> "%YÕ╣┤%b%dµùÑ %H:%M"

but at least it's something. It's trying to show Unicode characters, whereas strftime just ignores it:

> I18n.t(:'time.formats.long').encoding
=> #<Encoding:UTF-8>
> Time.now.strftime("").encoding
=> #<Encoding:Windows-1252>
Was it helpful?

Solution

  1. It's a readline (shipped with JRuby) issue, a simple fix is start irb with option --noreadline (Or add IRB.conf[:USE_READLINE] = false in your ~/.irbrc).

    C:\ConEmu>jirb
    irb(main):001:0> format = '%Y年%b%d日 %H:%M'
    => "%Y?b%d?%H:%M"                # Readline cannot handle GBK input here
    irb(main):002:0> exit
    
    C:\ConEmu>jirb --noreadline
    irb(main):001:0> format = '%Y年%b%d日 %H:%M'
    => "%Y年%b%d日 %H:%M"             # without Readline, it works
    irb(main):002:0> format.encoding
    => #<Encoding:GBK>
    irb(main):003:0> Time.now.strftime(format)
    => "2013??Jun20?? 23:20"         # strftime cannot process GBK input here
    
  2. strftime won't function well with a GBK encoded string. So encode the parameter to UTF-8 before passing it to strftime. BTW, it's very strange behavior that strftime returns GBK encoded string regardless of Encoding.default_internal!

    C:\ConEmu>jirb --noreadline
    irb(main):001:0> format = '%Y年%b%d日 %H:%M'
    => "%Y年%b%d日 %H:%M"
    irb(main):002:0> Time.now.strftime(format.encode('utf-8'))
    => "2013年Jun20日 23:32"
    
    irb(main):003:0> Time.now.strftime(format.encode('utf-8')).encoding
    => #<Encoding:GBK>
    irb(main):004:0> Encoding.default_internal = Encoding::UTF_8
    => #<Encoding:UTF-8>
    irb(main):005:0> Time.now.strftime(format.encode('utf-8')).encoding
    => #<Encoding:GBK>
    

I don't have Rails environment under JRuby, so I cannot help with the I18n encoding issue.

Readline is provided as JVM bytecode class files, as a result, you don't have easy way patching the library. So it is with strftime.

It's my first taste on JRuby (I was interested in the Encoding problem about Ruby), but I don't think I will pick it up ever again.

If you are finding some programming languages on JVM, you can take a look at Scala. It's more consistent, productive and creative, and (the most important compared to JRuby) less bug-prone in libraries.

Or if you are interested in Ruby, try RailsInstaller on Windows, or install RVM under Linux on a virtual machine. I'm sure you will find less trouble compared with JRuby, at least less Encoding trouble.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top