2013-07-22 21 views
-3

這是我在c#中的代碼。Java中的Convert.ToDateTime

DateTime gmtTime = Convert.ToDateTime(string.Format("{0} {1}", day[1], day[2])).Add(Convert.ToDateTime(time).TimeOfDay); 

我在Java中試過的東西。

String month = "Jul"; 
     String day = "22"; 
     String gmtTime = String.format("%s %s", month, day); 
     DateFormat df = new SimpleDateFormat("MMM dd"); 
     Date gmtDate = df.parse (gmtTime); 

我進入Java中的結果是1970年7月22日,我怎樣才能獲得本年度就像在C#,當我字符串轉換爲DATETIME年份是當前年份。有可能有一個代碼就像我在我的C#代碼試圖將其轉移到Java?

希望能得到好的結果。由於

+0

我爲什麼它被標記後實現.. – Sayse

+0

您沒有設置一年...只是把它添加到上面的代碼。 – DrColossos

+0

當把String轉換爲datetime時,是否可以像在c#中一樣自動設置當前年份? –

回答

1
Calendar cal=Calendar.getInstance(); 
int year=cal.get(Calendar.YEAR); 
System.out.println(year); 

使用的格式會給本年度

+0

感謝兄弟這是我想要的。 –

+1

@CarloAdap:很高興能幫到你! – xyz

0
final Date currentTime = new Date(); 
final SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a z"); 

// Set time zone 
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); 
System.out.println("Current Time: " + sdf.format(currentTime)); 

這裏簡單地格式化當前日期 -

final DateFormat reportDateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);   
Date date = new Date(); 
String dateString = reportDateFormat.format(date); 
System.out.println(dateString); 
1

更改這些行:

String gmtTime = String.format("%s %s", month, day); 
DateFormat df = new SimpleDateFormat("MMM dd"); 

要這樣:

String gmtTime = String.format("%s %s %s", month, day, Calendar.getInstance().get(Calendar.YEAR)); 
DateFormat df = new SimpleDateFormat("MMM dd yyyy"); 
+0

感謝bro @superEb –

相關問題