将日期格式的字符串更改为其他格式 [英] Change string in a date format to another format

查看:224
本文介绍了将日期格式的字符串更改为其他格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串(YYYYMMDD):

I have a string like this (YYYYMMDD):


20120225

20120225

我想要一个这样的字符串(MM / DD / YYYY):

And I want to have a string like this (MM/DD/YYYY):


02 / 25/2012

02/25/2012

在Ruby中有什么好的方法?我已经考虑过将第一个字符串转换为Date,然后更改格式。或者只是处理字符串并获取我想要的部分并构建新的字符串。

What's a good way of doing this in Ruby? I have thought about converting the first string to a Date, and then change the format. Or just treating the string and getting the parts I want and build the new string.

推荐答案

解析它然后格式化它是最好的解决方案:

Parsing it then formatting it is the best solution:

Date.parse("20120225").strftime("%m/%d/%Y")  #=> "02/25/2012"

这篇关于将日期格式的字符串更改为其他格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆