-2

I am trying to get this date 09/03/18 6:30:00 PM using 4-SEP-2018 but I am getting 12/364/17 6:30:00 PM, Here is what I have tried.

public class StockBuySell 

{      

    static String  DATE_FORMAT_UI = "DD-MMM-YYYY";


    public static void main(String args[]) throws Exception {

        DateFormat outputFormat = new SimpleDateFormat("MM/DD/YY h:mm:ss a");
        outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        DateFormat inputFormat = new SimpleDateFormat(DATE_FORMAT_UI);

        String inputText = "4-SEP-2018";
        Date date = inputFormat.parse(inputText);
        String outputText = outputFormat.format(date);
        System.out.println(outputText);

    }
}
saurabh kumar
  • 155
  • 5
  • 26
  • 3
    How are you supposed to get the time from the date? Or is it just the current time? Actually how can you possibly get `09/03/18 6:30:00 PM` from `4-SEP-2018`? Different date and a random time? – achAmháin Oct 05 '18 at 09:13
  • 2
    Watch your case... day in month is dd (not DD) and year is yy not YY – Michael Wiles Oct 05 '18 at 09:15
  • @achAmháin I feel like OP tries to use the date for timezone correction (09/03/18 6:30 PM + 5.5h = 09/04/18) –  Oct 05 '18 at 09:18
  • 1
    @Codeer perhaps...however, if that's the case, the question is poorly phrased. – achAmháin Oct 05 '18 at 09:19
  • @achAmháin I am giving time zone as GMT – saurabh kumar Oct 05 '18 at 09:22
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 05 '18 at 09:26
  • 1
    Learn about `LocalDate.parse` with `DateTimeFormatter.ofPattern`. Search Stack Overflow for many existing Questions and Answers. Always search Stack Overflow thoroughly before posting. – Basil Bourque Oct 05 '18 at 20:58

2 Answers2

2

As per the JavaDoc, D stands for Day in year. You will need to replace DD with dd (day in month).

Y stands for Week year, not year.

In short, this: "DD-MMM-YYYY" needs to be this: "dd-MMM-yyyy".

npinti
  • 51,780
  • 5
  • 72
  • 96
0

Try this:

String  DATE_FORMAT_UI = "dd-MMM-yyyy";

DateFormat outputFormat = new SimpleDateFormat("MM/dd/yy h:mm:ss a");
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
DateFormat inputFormat = new SimpleDateFormat(DATE_FORMAT_UI);

String inputText = "4-SEP-2018";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);
System.out.println(outputText);

You are going to have time zone issues as you're forcing the GMT... the date you're rendering will be in the local time zone so it may change the date.

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101