Reputation: 857
I need to convert time from GMT to PST and for that I am trying to subtract 7 hrs from the time. The issue is that the time is stored in a String and I am not sure how can I subtract 7 hrs from a String time. displayDateString
gives me the date and time and it is a String. I am trying the following approach but it is not working the way I need it.
Before Code Change
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
String displayDateString = formatDate(date, outputFormat);
DateFormat pstFormat = new SimpleDateFormat();
return displayDateString;
}
above code outputs: 06/02/17 07:19 PM
After Code Change
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
String displayDateString = formatDate(date, outputFormat);
DateFormat pstFormat = new SimpleDateFormat();
/*TimeZone pstZone = TimeZone.getTimeZone( "PST" );
pstFormat.setTimeZone( pstZone );
displayDateString = pstFormat.format(date);*/
Calendar cal = Calendar.getInstance();
cal = Calendar.getInstance();
cal.add( Calendar.HOUR, -7 );
displayDateString = pstFormat.format( cal.getTime() );
return displayDateString;
}
public static Date convertStringToDate(String strDate, String inputFormat) {
SimpleDateFormat dateFormat = null;
Date date = null;
boolean formatChagned = false;
try {
if(!StringUtils.isSet(strDate)){
return date;
}
if(strDate.indexOf("/")>0 && inputFormat.indexOf("-")>=0){
inputFormat = inputFormat.replaceAll("-", "/");
formatChagned=true;
}else if (strDate.indexOf("-")>0 && inputFormat.indexOf("/")>=0){
inputFormat = inputFormat.replaceAll("/", "-");
formatChagned=true;
}
dateFormat = new SimpleDateFormat(inputFormat);
dateFormat.setLenient(false);
date = dateFormat.parse(strDate);
} catch (Exception exception) {
log.error("Given date to parse:"+strDate);
log.error("Given Input Date Format:"+inputFormat);
if(formatChagned){
log.error("Given Input Date Format is incorrcet and it is modified as :"+inputFormat);
}
log.error(exception);
log.error("DateUtil.convertStringToDate :Parse exception while parsing,"+strDate+" using format :"+inputFormat);
date = null;
}
return date;
}
I added the calendar part to somehow subtract 7hrs from the existing time. This doesn't work.
Upvotes: 1
Views: 107
Reputation: 2447
You may change as following
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(displayDateString));
cal.add(Calendar.HOUR, -7);
Though
new Date(displayDateString)
is deprecated function
Upvotes: 1
Reputation: 1874
You need to set the calendar date before manipulating it:
cal.setTime(date);
before the:
cal.add( Calendar.HOUR, -7 );
And you seem to have some redundant code, like calling the Calendar getInstance twice.
Upvotes: 3