Human Being
Human Being

Reputation: 8387

Convert date and time in java

How can I convert the string,

yyyy/MM/dd HH:mm:ss:SSS

To,

MM/dd/yyyy HH:mm AM/PM

Hope our stack users will help me.

Upvotes: 1

Views: 1676

Answers (5)

Steve P.
Steve P.

Reputation: 14709

If you want to simply change the output format, you could use .format() from SimpleDateFormat:

SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = new SimpleDateFormat("MM/dd/yyyy HH:mm a").format(simple);

You do not specify if you actually want to use a Date object, but nonetheless, you can use the above method to perform the conversion that you desire.

If you wish to use a SimpleDateFormat, but actually want to change the internal format, use applyPattern():

simple.applyPattern("MM/dd/yyyy HH:mm a");

Upvotes: 1

Filip
Filip

Reputation: 877

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

public class Test {
    Test() throws ParseException {
  SimpleDateFormat sd = new SimpleDateFormat();
        String dateString = "2013-01-02 14:59:27.953";
        sd.applyPattern("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = sd.parse(dateString);
        sd.applyPattern("MM/dd/yyyy HH:mm a");
        System.out.println(sd.format(date));
    }

    public static void main(String[] args) {
        try {
           new Test();
        } catch(ParseException e) {
           System.err.println(e.getMessage());
        }
    }
}

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

Try this

  String dateTime="2013-01-02 14:59:27.953";
    DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
    Date date=df.parse(dateTime);
    df=new SimpleDateFormat("MM/DD/yyyy hh:mm a");
    System.out.println(df.format(date));
   }

Upvotes: 0

newuser
newuser

Reputation: 8466

Your time format is wrong MM for month, mm for minutes

MM/DD/YYYY HH:mm AM/PM

instead of

MM/DD/yyyy HH:MM AM/PM

Use SimpleDateFormat

Try this,

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/DD/yyyy HH:mm a");
System.out.println("Formated Date : "+simpleDateFormat.format(new Date()));

Upvotes: 0

AKDADEVIL
AKDADEVIL

Reputation: 206

    public static void main(String[] args) throws ParseException {
            SimpleDateFormat dfFrom = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"),
                            dfTo = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

            System.out.println(dfTo.format(dfFrom.parse("2013-01-02 14:59:27.953")));
    }

Regards,

AKDA

Upvotes: 1

Related Questions