Home > other >  How do you format a timestamp string to a Date object in Java?
How do you format a timestamp string to a Date object in Java?

Time:07-02

I'm creating a web service in Java using a Spring framework. It takes in an HTTP request with parameters 'payer', 'points', and 'timestamp'.

I need to store the data objects in a list and sort the list by timestamp, so I'm trying to convert the timestamp string to a Date object. Here's my current code:

String[] payers; // stores all payers
int totalPayers = 0; // number of payers in 'payers'

@GetMapping("/transaction")
    public void addTrans(@RequestParam(value="payer") String payer, @RequestParam(value="points") int points, @RequestParam(value="timestamp") String time) throws Exception{

        Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(time);
        
        Transaction newTrans = new Transaction(timestamp, payer, points);
        totalTrans  ;

        // if the payer is new, add them to the payers list
        boolean newPayer = true;
        for(int i = 0; i < totalPayers; i  ){
            if (payer == payers[i]){
                newPayer = false;
                break;
            }
        }
        if(newPayer){
            payers[totalPayers  ] = payer;
        }

        transactions.add(newTrans); // add the new transaction to the list
        totalPoints  = newTrans.getPoints();

        Collections.sort(transactions); // sort the list by timestamp

        return;
    }

When I run it, I'm getting the error:

java.text.ParseException: Unparseable date: "2020-11-02T14:00:00Z"

Does anyone know of something I may be missing? Is there an easier way to convert the string?

CodePudding user response:

You nee single quotes around the Z too.

Date timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(time);

The Z is not part of the pattern the function is supposed to recognize.

CodePudding user response:

Avoid legacy date-time classes

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date, SimpleDateFormat, etc.

java.time

Your input format complies with the ISO 8601 standard used by default in the java.time classes. So no need to specify a formatting pattern.

The T separates the date portion from the time-of-day portion. The Z on the end tells you the date and time is a moment as seen with an offset from UTC of zero hours-minutes-seconds. The Z is pronounced “Zulu” per aviation and military conventions.

Parsing text in standard ISO 8601 format:

String input = "2022-01-23T12:34:56Z" ;
Instant instant = Instant.now( input ) ;

Generating text in standard ISO 8601 format:

String output = instant.toString() ; 
  • Related