我可以得到輸出爲Wed May 11 15:36:08 IST 2016
,但我如何將日期轉換爲所需格式的字符串?如何解析給定的字符串格式爲dd-MMM-yyyy hh:mm:ss:aa?
要求的格式爲:12-05-2016 16:05:08 pm
我想的是什麼,
public class Test {
public static void main(String args[]) throws ParseException{
String epoche="1462961108000";
Long initialLogTime = Long.valueOf(epoche);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(initialLogTime);
Calendar fromDateTime = calendar;
Calendar toDateTime = fromDateTime;
toDateTime.add(Calendar.MINUTE, 30);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss:aa");
String datestring = String.valueOf(fromDateTime.getTime());
String datestring1 = String.valueOf(toDateTime.getTime());
System.out.println(datestring); //here output is Wed May 11 15:36:08 IST 2016
System.out.println(datestring1); // here output is Wed May 11 15:36:08 IST 2016
Date dates = dateFormat.parse(datestring);
Date date1s = dateFormat.parse(datestring1);
System.out.println(dates);
System.out.println(date1s);
}
}
我得到的錯誤是:
Exception in thread "main" java.text.ParseException: Unparseable date: "Wed May 11 16:05:08 IST 2016"
at java.text.DateFormat.parse(DateFormat.java:357)
at test.Test.main(Test.java:27)
你爲什麼要轉換成字符串,然後解析,當你已經擁有* *的價值?目前還不清楚這裏的最終目標是什麼......(如果只是將值格式化爲字符串,則根本不應該調用'parse')。 –
如前所述,應該使用方法調用SimpleDateFormat 'Date'對象上的'format()',而不是'String'對象上的'parse()',以獲得所需的結果 – Draken
如果使用SimpleDateFormat,請考慮它是格式化程序。它可以解析和格式化。解析意味着您將轉換爲類型實例,例如Date。格式意味着你基本上將它轉換成可讀形式,通常以字符串的形式。在你的情況下,你已經有了一個約會,所以你不需要像你想要做的那樣做任何中間步驟。 –