Java SimpleDateFormat decrementing date by one day

I am trying to reformat a date string using sdf. SDF is decrementing the date by a day. Pointers would be helpful.

java version "1.8.0_31" Input: ChangeDateStringFormat("10-Mar-2015");

Code:

public static String ChangeDateStringFormat (String Input) throws InterruptedException 
{           
    System.out.print("Input Date inside ChangeDateStringFormat : " + Input );

    SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("MST"));

    System.out.print(" || Output Date inside ChangeDateStringFormat : " +  sdf.format(new Date(Input)) + "\n");
    return sdf.format(new Date(Input));
}

Output Actual:

Input Date inside ChangeDateStringFormat : 10-Mar-2015 || Output Date inside ChangeDateStringFormat : Mar-09-2015

Output I was Expecting :

Input Date inside ChangeDateStringFormat : 10-Mar-2015 || Output Date inside ChangeDateStringFormat : Mar-10-2015

Jon Skeet
people
quotationmark

This is the problem:

new Date(Input)

You should not use that. Instead, construct a SimpleDateFormat to parse your input:

import java.text.*;
import java.util.*;

public class Test {
    public static void main(String[] args) throws ParseException {
        System.out.println(convertDateFormat("10-Mar-2015"));
    }

    public static String convertDateFormat(String input) throws ParseException {
        TimeZone zone = TimeZone.getTimeZone("MST");
        SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
        inputFormat.setTimeZone(zone);
        SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy", Locale.US);
        outputFormat.setTimeZone(zone);

        Date date = inputFormat.parse(input);
        return outputFormat.format(date);
    }
}

However:

  • If you're just parsing a date, you'd be better of specifying UTC as the time zone; you don't want to end up with problems due to time zones that switch DST at midnight
  • If you're going to run this code on Java 8 and nothing lower, I'd strongly recommend using java.time instead of Date, Calendar etc.

people

See more on this question at Stackoverflow