In a field the date and time is set like "10/9/2014 7:43 PM".
在字段中,日期和时间设置为“10/9/2014 7:43 PM”。
I want to remove the time and need only the date so that I compare it with today's date. I.e., I want only "10/9/2014"
.
我想删除时间,只需要日期,以便将其与今天的日期进行比较。即,我只想要“10/9/2014”。
Could anyone suggest how to do it?
谁能建议怎么做?
3 个解决方案
#1
2
Is it a string or a DateTime object?
它是字符串还是DateTime对象?
If it's a DateTime object, just use to_date
that will convert it to date:
如果它是一个DateTime对象,只需使用to_date将其转换为日期:
myDate.to_date
If it's a String, just split
it and get the first part:
如果它是一个字符串,只需拆分它并得到第一部分:
"10/9/2014 7:43 PM".split(' ').first
=> "10/9/2014"
#2
1
I'd do
我会做
require 'date'
date = Date.parse "10/9/2014 7:43 PM"
# => #<Date: 2014-09-10 ((2456911j,0s,0n),+0s,2299161j)>
date.to_s # => "2014-09-10"
Another way using Date::strptime
另一种使用Date :: strptime的方法
date = Date.strptime("10/9/2014 7:43 PM", "%d/%m/%Y %l:%M %p")
# => #<Date: 2014-09-10 ((2456911j,0s,0n),+0s,2299161j)>
date.to_s # => "2014-09-10"
#3
0
You can format the date:
您可以格式化日期:
d = DateTime.new(2014, 10, 9, 7, 43, 0)
d.strftime("%m/%d/%Y") -> Gives "10/09/2014
or you can do d.strftime("%D")
或者你可以做d.strftime(“%D”)
#1
2
Is it a string or a DateTime object?
它是字符串还是DateTime对象?
If it's a DateTime object, just use to_date
that will convert it to date:
如果它是一个DateTime对象,只需使用to_date将其转换为日期:
myDate.to_date
If it's a String, just split
it and get the first part:
如果它是一个字符串,只需拆分它并得到第一部分:
"10/9/2014 7:43 PM".split(' ').first
=> "10/9/2014"
#2
1
I'd do
我会做
require 'date'
date = Date.parse "10/9/2014 7:43 PM"
# => #<Date: 2014-09-10 ((2456911j,0s,0n),+0s,2299161j)>
date.to_s # => "2014-09-10"
Another way using Date::strptime
另一种使用Date :: strptime的方法
date = Date.strptime("10/9/2014 7:43 PM", "%d/%m/%Y %l:%M %p")
# => #<Date: 2014-09-10 ((2456911j,0s,0n),+0s,2299161j)>
date.to_s # => "2014-09-10"
#3
0
You can format the date:
您可以格式化日期:
d = DateTime.new(2014, 10, 9, 7, 43, 0)
d.strftime("%m/%d/%Y") -> Gives "10/09/2014
or you can do d.strftime("%D")
或者你可以做d.strftime(“%D”)