在 java 程序中使用 java.util.Date 格式将日期格式"2015/07/02"转换为"02-JUL-15"



我想用java代码更改日期格式。

输入值为"2015/07/02"。

输出值希望为"02- july -15"。

我想知道"02- july -15"的日期格式。如何更改日期格式?请帮助!

最简单的方法是在java中使用SimpleDateFormat

DateFormat date = new SimpleDateFormat("dd-MMM-yy");
date.format(yourdate); //yourdate in this case is "2015/07/02" wherever that is stored

回答你的问题," 02-07-15 "的格式是dd-MMM-yy,尽量不要使用java.util.date,它的大部分方法已经被弃用

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * This Example
 * Takes an input in the format YYYY/MM/DD i.e 2015/07/24
 * and converts back in the format DD-MON-YY ie 24-JUL-15
 */
public class DateConverter1 {
    public static void main(String...strings) throws ParseException {
        // define the date format in which you want to take the input
        // i.e YYYY/MM/DD correspond to yyyy/MM/dd
        DateFormat inputDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        // convert your date into desired input date format
        Date inputDate = inputDateFormat.parse("2015/07/20");
        // above lines gives Parse Exception if date is UnParsable

        // define the date format in which you want to give output
        // i.e dd-MMM-yy
        DateFormat outputDateFormat = new SimpleDateFormat("dd-MMM-yy");
        // don't assign it back to date as format return back String
        String outputDate = outputDateFormat.format(inputDate);
        System.out.println(outputDate);

    }
}
输出:

20-Jul-15

@ ankur Anand And @现在,我找到了关于"dd-MMM-yy"的解决方案。当我们在我的电脑的区域和语言设置格式"英语(美国)"时,我们发现输出"20- july -15"。但是,当我们在区域和语言上设置"日语"格式时,我们发现输出"20-07-15"。

最新更新