Change date format in a Java string

2018-12-31 00:14发布

I've a String representing a date.

String date_s = "2011-01-18 00:00:00.0";

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?


Okay, based on the answers I retrieved below, here's something I've tried:

String date_s = " 2011-01-18 00:00:00.0"; 
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date date = dt.parse(date_s); 
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

16条回答
何处买醉
2楼-- · 2018-12-31 00:37

You can also use substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

If you want a space in front of the date, use

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);
查看更多
不流泪的眼
3楼-- · 2018-12-31 00:38
private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(value instanceof Date) {
        value = dataFormat.format(value);
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 00:41

You can just use:

Date yourDate = new Date();

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);

It works perfectly!

查看更多
裙下三千臣
5楼-- · 2018-12-31 00:41

You could try java 8 new date, more information can be found on the oracle documentation.

Or you can try the old one

public static Date getDateFromString(String format, String dateStr) {

        DateFormat formatter = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = (Date) formatter.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    public static String getDate(Date date, String dateFormat) {
        DateFormat formatter = new SimpleDateFormat(dateFormat);
        return formatter.format(date);
    }
查看更多
登录 后发表回答