Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

I want to convert a string to date format in java 6

My Input is like this:

20180718140032488266000Z-0600

and the way it should go and persist in database is like this:

21-JUL-18 12.05.25.000000000 AM

Currently I have written code like this :

    public static void main(String[] argv) throws ParseException {
        // SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSSZ");
        String dateInString = "20180718140032488266000Z-0600";
        Timestamp ts = formatDate(dateInString);
        System.out.println(ts);
    }

    private static Timestamp formatDate(String dateString) throws ParseException {
        // dateString = dateString.replaceAll("Z", "0000");
        SimpleDateFormat fmtTimestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS'Z'");
        Date dtTimestamp1 = fmtTimestamp.parse(dateString);
        Timestamp timestamp = new java.sql.Timestamp(dtTimestamp1.getTime());
        return timestamp;
    }

I am getting an output in this format: 2018-07-24 05:38:18.0, my question is how can I get AM/PM also in the output. Please suggest solutions. I will be really grateful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The below code will give you date in '2018-07-31 7:39:09 PM' format.Kindly refer http://tutorials.jenkov.com/java-internationalization/simpledateformat.html#formatting-dates for additional info

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd h:mm:ss a");
    String strDate= formatter.format(date);
    System.out.println(strDate);
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...