Pacific-Design.com

    
Home Index

1. Java

2. DateFormat

+ Today

Java / DateFormat /

DateFormat.java

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormat {

    /*----------------------------------------------------------------------------------*/
    public static void main(String[] args) throws IOException, ParseException {

        String date1 = format_datetime("Sun Mar 10 04:03:23 2013");
        String date2 = format_gmt_datetime("Thu Jun 18 23:16:12 EDT 2011"); //converts to PST
        
        System.out.println(date1);
        System.out.println(date2);
    }
    /*----------------------------------------------------------------------------------*/

    private static String format_datetime(String str) throws ParseException {

        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
        Date date = formatter.parse(str);

        String formattedString = formatter.format(date);
        Date newDate = formatter.parse(formattedString);

        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formattedString = formatter.format(newDate);

        return formattedString;

    }
    /*----------------------------------------------------------------------------------*/

    private static String format_gmt_datetime(String str) throws ParseException {

        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = formatter.parse(str);

        String formattedString = formatter.format(date);
        Date newDate = formatter.parse(formattedString);

        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formattedString = formatter.format(newDate);
        
        return formattedString;
    }
    /*----------------------------------------------------------------------------------*/
}

Output

2013-03-10 04:03:23
2011-06-18 20:16:12