Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading