时间戳格式

问题描述 投票:0回答:4

您能否建议如何以“dd MonthName”格式显示时间戳值,例如“2013 年 6 月 25 日星期二 21:56:17 IST”。应显示为“25 June”。我正在使用下面的代码,但它不起作用。

Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("d M");
System.out.println("Current Date: " + ft.format(dNow));

观察到的输出:

当前日期:25 6

java date simpledateformat date-formatting
4个回答
2
投票

您使用了错误的模式。你的模式应该是:

SimpleDateFormat ft = new SimpleDateFormat ("dd MMM");

1
投票

使用格式为

"dd MMMMM"

dd:一个月中的第几天(2 位数字)

MMMMM:一年中的月份

SimpleDateFormat sdf = new SimpleDateFormat ("dd MMMMM");

在此处阅读有关 SimpleDateFormat 的更多信息

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html


1
投票

“6 月 25 日”的模式应该是:

SimpleDateFormat ft = new SimpleDateFormat ("d MMMM");

1
投票

tl;博士

java.time

MonthDay
可以捕获当前月份和日期,然后生成本地化文本。

MonthDay
.now( ZoneId.of( "Asia/Tokyo" ) )
.format( 
    DateTimeFormatter
    .ofPattern( "d MMMM" )
    .withLocale( Locale.of( "fr" , "CA" ) )  // French language, Canada cultural norms.
)

查看此代码在 Ideone.com 上运行

10月16日

避免遗留类

永远不要使用有严重缺陷的遗留日期时间类。避免

Date
Calendar
SimpleDateFormat

java.time

仅使用 JSR 310 中定义并内置于 Java 8+ 中的现代 java.time 类。

MonthDay

对于月份和月份中的某一天,使用

MonthDay
类。

ZoneId

要获取当前月份和日期,请指定时区。对于任何给定时刻,全球各地的时间和日期都会因时区而异。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
MonthDay currentMonthDay = MonthDay.now( z ) ;

ISO 8601

要生成标准 ISO 8601 格式的文本,只需调用

toString

String output = currentMonthDay.toString() ;

DateTimeFormatter

要生成本地化文本,例如

25 June
,请定义格式化模式。

Locale

指定

Locale
以确定本地化中使用的人类语言和文化规范。

Locale locale = Locale.of( "en" , "US" ); 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d MMMM" ).withLocale( locale ) ;
String output = currentMonthDay.format( f ) ;

查看代码 在 Ideone.com 上运行

10 月 16 日

© www.soinside.com 2019 - 2024. All rights reserved.