0 votes
171 views
asked in JAVA by
Hi all

   How to calculate one hour ago time from an string array in java which holds value from database

1 Answer

0 votes
answered by (4.2k points)
String sDate = "2014-09-02 15:19:59.000";
String format = "yyyy-MM-dd HH:mm:ss.SSS";
DateTime oDate = DateTime.parse(sDate,
        DateTimeFormat.forPattern(format));
System.out.println( oDate.minusHours(1).toString(format));

prints

2014-09-02 14:19:59.000

the imports

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

If you cannot use DateTime, the solution using only java.util would be as kriyeta suggests, just some fixes:

String sDate = "2014-09-02 15:19:59.000";
String format = "yyyy-MM-dd HH:mm:ss.SSS";    
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(sDate);
Calendar calendar=Calendar.getInstance();
calendar.setTime(date); 
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--; 
calendar.set(Calendar.HOUR_OF_DAY, hours);
Date fixedDate=calendar.getTime(); 
System.out.println(simpleDateFormat.format(fixedDate));

With respect to the comment, to have the output look the same you need to align the formats so either

System.out.println(date + "-" + fixedDate); // Tue Sep 02 15:19:59 CEST 2014-Tue Sep 02 14:19:59 CEST 2014

or

 System.out.println(simpleDateFormat.format(date) + "-" + simpleDateFormat.format(fixedDate)); // 2014-09-02 15:19:59.000-2014-09-02 14:19:59.000

but you have a complete control over how the dates are represented as strings, so don't let that confuse you, the only important thing is to get your Date instances right

Categories

...