Domanda

Hi I am trying to convert a string 19611015 to a date formate of ("yyyy-MM-dd HH:mm:ss") before storing it into a sybase database table. I have tried the below code which gives me the error:

Unparseable date: "19611015"

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

I have been reading some long and complex solutions to this, some suggesting to use Locale. Could someone explain maybe an alternative simple solution to convert string I have to a date format I am after above. Thank you.

È stato utile?

Soluzione

The date in string is in yyyyMMdd format and want to convert it into yyyy-MM-dd HH:mm:ss so use below code :

        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);

Output :

1961-10-15 00:00:00

Altri suggerimenti

Achilles, below code might solve your problem:

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
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top