仅显示DateTime值的年 - 月 - 日

时间:2013-12-03 11:05:16

标签: scala jodatime

我有这段代码:

order.bookingDate()

我得到了这个:2013-11-22T10:15:00.000-08:00

但我只是想在网页上显示:2013-11-22,如果可以采用这种格式:22-11-2013,有什么想法吗?谢谢!

6 个答案:

答案 0 :(得分:4)

dateTime.ToString("yyyy-MM-dd");

如果您在字符串中有日期时间,请先将其转换为日期时间,如下所示

DateTime dateTime;
dateTime = new DateTime();
dateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

日期格式

d - Numeric day of the month without a leading zero.
dd - Numeric day of the month with a leading zero.
ddd - Abbreviated name of the day of the week.
dddd - Full name of the day of the week.

M - Numeric month with no leading zero.
MM - Numeric month with a leading zero.
MMM - Abbreviated name of month.
MMMM - Full month name.

y - Year with out century and leading zero.
yy - Year with out century, with leading zero.
yyyy - Year with century.

时间格式

h - 12 Hour clock, no leading zero.
hh - 12 Hour clock with leading zero.
H - 24 Hour clock, no leading zero.
HH - 24 Hour clock with leading zero.

m - Minutes with no leading zero.
mm - Minutes with leading zero.

s - Seconds with no leading zero.
ss - Seconds with leading zero.

t - AM/PM but only the first letter. 
tt - AM/PM ( a.m. / p.m.)

zz - Time zone off set with +/-

答案 1 :(得分:2)

使用DateTimeFormat对象:

val fmt = DateTimeFormat.forPattern("yyyy-MM-dd")
fmt.print(order.bookingDate())

您可以将DateTimeFormat字段中的object对象保存为全局常量,它是线程安全的。或者您可以直接使用toString()方法:

order.bookingDate().toString("yyyy-MM-dd")

有关可能的日期/时间模式的详细信息,请参阅DateTimeFormat API文档(上面的链接)。例如,这种格式:22-11-2013可以通过颠倒前面示例中的格式模式轻松实现:

order.bookingDate().toString("dd-MM-yyyy")

答案 2 :(得分:1)

您可以使用正则表达式进行模式匹配并获得所需内容。例如:

val rawDate = "2013-11-22T10:15:00.000-08:00" //order.bookingDate() or order.bookingDate().toString

val YMD = """(\d\d\d\d)-(\d\d)-(\d\d).*""".r // Three capture groups of 4,2, and 2 digits, followed by stuff we don't care about ('.*')

val YMD(y, m, d) = rawDate // unapply to store the captured groups into new vals y, m, d

val outStr = s"$d-$m-$y" // outStr = "22-11-2013"

答案 3 :(得分:1)

您可以在ToString()方法中使用您的格式:

order.bookingDate.ToString("yyyy-MM-dd")

答案 4 :(得分:0)

使用Joda,

import org.joda.time.DateTime
val dt = new DateTime("2013-11-22T10:15:00.000-08:00")

然后

dt.toYearMonthDay.toString
String = 2013-11-22

dt2.getDayOfMonth + "-" + dt2.getMonthOfYear + "-" + dt2.getYear
String = 22-11-2013

答案 5 :(得分:0)

from datetime import datetime - `datetime.now()` Expected Output : 2018-11-15T11:14:00.000-08:00 Need only date: - `datetime.date(datetime.now())`

如果您需要去除日期,年份或时间,并根据需要进行排列。尝试调整所需位置的值。 您可以执行以下操作:

- `datetime.now().strftime("%Y-%m-%d-%H-%M")` Expected Output: YYYY-MM-DD-HH-MM '2018-11-15-11-14'