[英]Format a Date and returning a Date, not a String
我需要使用以下格式“ yyyy-MM-dd'T'HH:mm:ss”獲取當前時間的日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
我知道如何使用SimpleDateFormat格式化日期。 最后,我得到一個字符串。 但是我需要獲取格式化的日期,而不是字符串,據我所知,我無法將字符串轉換回日期,可以嗎?
如果我只返回日期,則它是一個日期,但格式不正確:
Timestamp ts = new Timestamp(new Date().getTime());
編輯:不幸的是,我需要將結果作為Date而不是String ,所以我不能使用sdf.format(New Date()。getTime()),因為這會返回String。 另外,我需要返回的日期是當前時間的日期,而不是靜態字符串。 我希望這可以澄清
試試這個
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = sdf.parse("2016-03-10....");
但是我需要獲取格式化的日期,而不是字符串,據我所知,我無法將字符串轉換回日期,可以嗎?
由於您知道DateTime格式,因此實際上很容易將Date格式設置為String,反之亦然。 我個人將使用字符串到日期和日期到字符串轉換方法創建一個單獨的類:
public class DateConverter{
public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static Date convertStringToDate(final String str){
try{
return DATE_FORMAT.parse(str);
} catch(Exception ex){
//TODO: Log exception
return null;
}
}
public static String convertDateToString(final Date date){
try{
return DATE_FORMAT.format(date);
} catch(Exception ex){
//TODO: Log exception
return null;
}
}
}
用法:
// Current date-time:
Date date = new Date();
// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);
// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);
ZonedDateTime.now() // Capture the current moment as seen by the people of a region representing by the JVM’s current default time zone.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).
現代方法使用java.time類。
在UTC中捕獲當前時刻。
Instant instant = Instant.now() ;
通過特定地區(時區)的人們使用的掛鍾時間查看同一時刻。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
您想要生成一個表示此值的字符串,其格式缺少時區或UTC偏移量。 我不建議這樣做。 除非用戶閱讀的上下文對隱式區域/偏移量絕對清楚,否則您將在結果中引入歧義。 但是,如果您堅持認為,則java.time類為該格式化模式預定義了一個格式化程序對象: DateTimeFormatter.ISO_LOCAL_DATE_TIME
。
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.Date
, Calendar
和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參見Oracle教程 。 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310 。
您可以直接與數據庫交換java.time對象。 使用與JDBC 4.2或更高版本兼容的JDBC驅動程序 。 不需要字符串,不需要java.sql.*
類。
在哪里獲取java.time類?
要格式化數據字段,請執行以下操作
Date today = new Date();
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String date2= DATE_FORMAT.format(today);
Date date;
try {
date = DATE_FORMAT.parse(date2);
setDate(date); //make use of the date
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以上對我來說很完美。
解析方法應該對您可用。 使用intellisense檢查您的對象具有哪些方法:)或僅查看javadoc,大多數IDE都可以選擇打開java文件。
String dateString = "2016-01-01T00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(dateString);
嘗試這個:
LocalDateTime ldt = Instant.now()
.atZone(ZoneId.systemDefault())
.toLocalDateTime()
如果要將String
轉換為Date
,則需要使用DateFormat
以String
格式解析Date
。 這是一個例子-
String target = "2016-03-10T15:54:49";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date result = df.parse(target);
public String getCurrentDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// get current date time with Date()
Date date = new Date();
return dateFormat.format(date);
}
時間格式應該相同,否則會出現時間解析器異常
String dateString = "03/26/2012 11:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch t(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(convertedDate);
使用我的代碼,希望它對您有用...
SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
String str_date=dateFormat.format(new Date());
是的,您可以:)您可以將字符串轉換回日期。
此方法將幫助您: Date parse(String date);
它返回Date類對象。 您只需要在此方法中以String格式傳遞日期。
import java.text.*;
import java.util.*;
class Test {
public static void main(String[] args) throws Throwable {
String date = "2016-03-10T04:05:00";
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = s.parse(date);
System.out.println(d);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.