Exception of an exceptional date when converting a string to "yyyy-MM-dd HH: mm: ss"

Hi, I am trying to convert the string 19611015 to a date form ("yyyy-MM-dd HH: mm: ss") before storing it in the sybase database table. I tried the code below that gives me an error:

Unbeatable Date: "19611015"

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.parse("19611015"));

I read some long and complicated solutions for this, some suggested using Locale. Could someone please explain maybe an alternative simple solution for converting the string that I have to the date format I am above. Thanks.

+4
source share
2 answers

date yyyyMMdd yyyy-MM-dd HH: mm: ss, :

        DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
        DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = originalFormat.parse("19611015");
        String formattedDate = targetFormat.format(date); 
        System.out.println(formattedDate);

:

1961-10-15 00:00:00
+6

, :

package com.test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LongToDate {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(19611015 * 1000);
        String dateFormatString = "yyyy-MM-dd HH:mm:ss";
        DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
        String result = dateFormat.format(cal.getTime());
        System.out.println(result);
        //Output: 1969-12-10 15:46:18
    }
}
0

Source: https://habr.com/ru/post/1527296/


All Articles