Is DateTime.parse() in Ruby dependent on locale?

旧时模样 提交于 2019-12-22 18:02:19

问题


I'm wondering regarding the output of the following example: when parsing 01/03, will it be resolved as Mar, 1st or Jan, 3rd?


回答1:


Ruby is not locale dependent. Because Ruby is a server-side language and not a client-side language like JavaScript, Ruby uses the system clock from your web app server - and uses this information to calculate the time. Whatever timezone you have your system set to is what your Ruby app will use.

When parsing a date from a string, DateTime will make its best guess based on how the input is formatted:

DateTime.parse('01/03')
#=> Thu, 03 Jan 2019 00:00:00 +0000

DateTime.parse('2019/01/03')
#=> Thu, 03 Jan 2019 00:00:00 +0000

DateTime.parse('01/03/2019')
#=> Fri, 01 Mar 2019 00:00:00 +0000

You can also explicitly tell DateTime how you want your string parsed using strptime:

date = '01-03-2019'

DateTime.strptime(date, '%m-%d-%Y')
#=> Thu, 03 Jan 2019 00:00:00 +0000

DateTime.strptime(date, '%d-%m-%Y')
#=> Fri, 01 Mar 2019 00:00:00 +0000


来源:https://stackoverflow.com/questions/22482532/is-datetime-parse-in-ruby-dependent-on-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!