2014-02-16 151 views
1

我有一个字符串timeStamp,格式为“Wed,29 Jan 2014 20:14:15 GMT”。我希望能够将此日期与此格式01/25/1999中的另一个日期进行比较。我试过simpledateformatter但没有成功。从TimeStamp获取月份和日期

String a = connection.getHeaderField("Last-Modified"); //Returns Wed, 29 Jan 2014 20:14:15 GMT 
Date lastModDate = new Date(file.lastModified()); //returns 01/25/1999 

这是我试图实现

SimpleDateFormat formatter; 
Date dateIn = null; 
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US); 
try{ 
dateIn = (Date)formatter.parse(a); 

}catch(ParseException e){ 
e.printStackTrace(); 
} 
Log.d(TAG, "The server date is formated to : " + dateIn); 

的dateIn总是空的simpleDateFormatter。

我希望能够做这样的事

SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy"); 
Date strDate = sdf.parse(valid_until); 
if (new Date().after(strDate)) { 

} 
+0

您的标题与您的问题不符。 –

回答

1

使用下面的代码...你会得到问题吧。

Calendar calender = Calendar.getInstance(); 
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 

String timeStamp = formatter.format(calender.getTime()); 
Date strDate = formatter.parse(timeStamp); 

String currentTimeStamp = formatter.format(new Date()); 
Date currentTime = formatter.parse(currentTimeStamp); 

if (currentTime.after(strDate)) { 

} 
1

不知道你尝试过什么,但是这应该工作:

String a = connection.getHeaderField("Last-Modified"); 
Date date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).parse(a); 

这可以帮助http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

+0

代码工作,但我不得不做java.util.Date日期=新SimpleDateFormat()... – Amit625

+0

好吧,我看到我的错误,我不知道“java.util.Date和java.sql.Date” – Amit625

0

你应使用Calendar类及其子类GregorianCalendar。例如,要获得您的日期的月份:

Calendar cal = new GregorianCalendar(); 
cal.setTime(date); 
cal.get(Calendar.MONTH); 
+0

我试过这个,但是如果日期的格式是这样的“Wed Jan 29 15:14:15 EST 2014”。上面的代码由于某种原因返回0? – Amit625

+0

它不应该发布代码 –

1

原因是您的格式化程序使用了错误的日期格式。如果您收到的日期看起来像

"Wed, 29 Jan 2014 20:14:15 GMT" 

那么你应该使用以下格式

formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);