我一直在开发使用此代码的Android应用程序:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(d);
我需要在当前时刻8小时后获取日期,我希望这个日期有24小时格式,但我不知道我是如何通过SimpleDateFormat制作的。我还需要该日期格式为DD/MM/YYYY HH:MM:SS
。
答案 0 :(得分:52)
这将以24小时格式为您提供日期。
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
答案 1 :(得分:51)
12小时格式:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);
24小时格式:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);
答案 2 :(得分:12)
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH将持续0-23小时。
kk将在1-2小时内返回。
在此处查看更多内容:Customizing Formats
使用方法 setIs24HourView(布尔值为24HourView)设置时间选择器以设置24小时视图。
答案 3 :(得分:4)
尝试以下代码
String dateStr = "Jul 27, 2011 8:35:29 PM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse( dateStr );
} catch ( ParseException e ) {
e.printStackTrace();
}
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format( date );
}
System.out.println(formattedDate);
祝你好运!!!
检查各种formats。
答案 4 :(得分:4)
在格式化程序字符串中使用HH而不是hh
答案 5 :(得分:2)
现代方法使用 java.time 类。
Instant.now() // Capture current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( 8 , ChronoUnit.HOURS ) // Add eight hours.
.atZone( ZoneId.of( "America/Montreal" ) ) // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
.withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated.
) // Returns a `String` object.
23/01/2017 15:34:56
仅供参考,旧的Calendar
和Date
课程现在为legacy。被java.time类取代。大部分java.time都被反向移植到Java 6,Java 7和Android(见下文)。
Instant
使用Instant
类捕获UTC中的当前时刻。
Instant instantNow = Instant.now();
instant.toString():2017-01-23T12:34:56.789Z
如果你只需要整秒,不需要任何一秒,就截断。
Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
instant.toString():2017-01-23T12:34:56Z
Instant
班可以做数学,增加一些时间。指定ChronoUnit
枚举添加的时间量,TemporalUnit
的实现。
instant = instant.plus( 8 , ChronoUnit.HOURS );
instant.toString():2017-01-23T20:34:56Z
ZonedDateTime
要通过特定区域的挂钟时间透镜查看同一时刻,请应用ZoneId
获取ZonedDateTime
。
以continent/region
的格式指定proper time zone name,例如America/Montreal
,Africa/Casablanca
或Pacific/Auckland
。切勿使用诸如EST
或IST
之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString():2017-01-23T15:34:56-05:00 [美国/蒙特利尔]
您可以通过在DateTimeFormatter
对象中指定格式设置模式,以所需格式生成字符串。
请注意格式设置字母中的大小写。问题代码的hh
为12小时,大写HH
为java.time.DateTimeFormatter
的24小时时间(0-23)以及遗留java.text.SimpleDateFormat
。
java.time中的格式代码与旧版SimpleDateFormat
中的格式代码类似,但不完全相同。仔细研究课程文档。在这里,HH
恰好相同。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );
不要硬编码格式化模式,而是考虑让 java.time 通过调用DateTimeFormatter.ofLocalizedDateTime
完全本地化String
文本的生成。
顺便说一下,请注意时区和Locale
没有彼此相关;正交问题。一个是关于内容,意思(挂钟时间)。另一个是关于演示,确定用于向用户呈现该含义的人类语言和文化规范。
Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" ); // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ); // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );
instant.toString():2017-01-23T12:34:56Z
zdt.toString():2017-01-24T01:34:56 + 13:00 [太平洋/奥克兰]
输出:mardi 24 janvier2017à01:34:56heureavancéedela Nouvelle-Zélande
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和& SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
从哪里获取java.time类?
更新:Joda-Time项目现在位于maintenance mode,团队建议迁移到java.time类。
Joda-Time使这项工作变得更加轻松。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );
System.out.println( "laterAsText: " + laterAsText );
跑步时......
laterAsText: 19/12/2013 02:50:18
请注意,此语法使用默认时区。更好的做法是使用显式的DateTimeZone实例。
答案 6 :(得分:1)
LocalDateTime#plusHours
LocalDateTime
以 ISO-8601 standards 为模型,并作为 JSR-310 implementation 的一部分与 Java-8 一起引入。
使用 LocalDateTime#plusHours
获取添加了指定小时数的此 LocalDateTime
的副本。
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the timezone of your JVM. It is also the
// default timezone for date-time type i.e.
// LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
// Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldt);
LocalDateTime after8Hours = ldt.plusHours(8);
System.out.println(after8Hours);
// Custom format
DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
System.out.println(dtfTimeFormat24H.format(after8Hours));
System.out.println(dtfTimeFormat12h.format(after8Hours));
}
}
输出:
2021-01-07T15:24:52.736612
2021-01-07T23:24:52.736612
07/01/2021 23:24:52
07/01/2021 11:24:52 PM
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
使用旧 API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date currentDateTime = calendar.getTime();
System.out.println(currentDateTime);
// After 8 hours
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date after8Hours = calendar.getTime();
System.out.println(after8Hours);
// Custom formats
SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Change the timezone as per your requirement e.g.
// TimeZone.getTimeZone("Europe/London")
sdf24H.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
sdf12h.setTimeZone(TimeZone.getDefault());
System.out.println(sdf24H.format(after8Hours));
System.out.println(sdf12h.format(after8Hours));
}
}
输出:
Thu Jan 07 15:34:10 GMT 2021
Thu Jan 07 23:34:10 GMT 2021
07/01/2021 23:34:10
07/01/2021 11:34:10 PM
String
。
java.time.format
例如java.time.format.DateTimeFormatter
、java.time.format.DateTimeFormatterBuilder
等java.text
例如java.text.SimpleDateFormat
、java.text.DateFormat
等java.util.Date
对象不是像 modern date-time types 那样的真实日期时间对象;相反,它表示从 Epoch of January 1, 1970
开始的毫秒数。当您打印 java.util.Date
的对象时,它的 toString
方法返回 JVM 时区中的日期时间,从这个毫秒值计算出来。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFormat
并从中获取格式化的字符串。java.util
的日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API。
答案 7 :(得分:0)
你可以这样做:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);
这里'kk:mm:ss'是正确答案,我对Oracle数据库感到困惑,抱歉。
答案 8 :(得分:0)
试试这个......
Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
"MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);
答案 9 :(得分:0)
您需要做的就是将模式中的小写“hh”更改为大写字母“HH”
对于 Kotlin:
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())
对于Java:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())