簡體   English   中英

將Java Date轉換為另一個Time as Date格式

[英]Convert Java Date into another Time as Date format

我想將日期轉換為“印度時間”。 具體來說:“亞洲/加爾各答”。

碼:

// TODO Auto-generated method stub
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));

String dateString=simpleDateFormat.format(date);

System.out.println("Currect Date : " + dateString);
// This is returning a string and I want a date.

System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString)); 
//This returns a Date but has incorrect result.

這是上面代碼的輸出:

Correct Date : 2013-04-15 15:40:04
Wrong Output : Mon Apr 15 03:10:04 MST 2013

我想要DATE,而不是字符串,但是當我檢索日期時,時間是3:10 ,而當我得到字符串時,我得到15:40:04 為什么這些不一樣?

parse()分析日期文本並構造一個Date對象,該對象是一個長值。 parse()javadoc說

The TimeZone value may be overwritten, depending on the given pattern and 
the time zone value in text. Any TimeZone value that has previously been 
set by a call to setTimeZone may need to be restored for further operations.

通過在Date上調用toString()來打印解析的Date對象,該對象已在MST時區中打印。 如果將其從MST轉換為IST,那么您將獲得期望的時間戳。 因此,您的輸出是正確的。 您所需要做的就是使用正確的時區格式化並打印您的長日期值。

解析將返回一個DateObject,因此調用:

System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString));

有點類似於:

Date d1 = simpleDateFormat.parse(dateString);
System.out.println("Wrong Output : "+d1.toString());

請記住,解析日期只是解析字符串以生成日期對象,如果要以某種格式顯示它,請使用該日期對象並對其調用sdf.format。 例如

 String dateStringOut=simpleDateFormat.format(d1);
 System.out.println("Output : "+dateStringOut);

Date不包含任何格式。 它只是一個Date 因此,您不能在不同的輸出格式之間轉換Date對象。 確定日期后,就無需嘗試將其轉換為其他格式。 如何格式化它,取決於何時使用SimpleDateFormat將其轉換為String 因此,一旦您解析了Date ,就保留它,直到需要格式化它以便輸出為止。

使用DateFormat類的靜態函數getDateTimeInstance(int dateStyle,int timeStyle)。 有關更多詳細信息,請參見DateFormat類。 它可能會幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM