如何在java中将字符串日期2015-02-12转换为12-02-2015

时间:2015-02-06 06:54:58

标签: java

如何在java中将字符串日期2015-02-12转换为12-02-2015 我从日期选择器的一个表格中取日期,结果是字符串日期 像2014-02-19,但我想在19-02-2014显示日期

4 个答案:

答案 0 :(得分:3)

您可以使用SimpleDateFormat,并将给定日期解析为所需格式。

public static void main(String[] args) throws ParseException {
        SimpleDateFormat givenFormat = new SimpleDateFormat("yyyy-mm-dd");
        Date givendate = givenFormat.parse("2015-02-12");
        SimpleDateFormat ouputFormat = new SimpleDateFormat("dd-mm-yyyy");
        String newDate = ouputFormat.format(givendate);
        System.out.println(newDate);
    }

<强>输出

12-02-2015

答案 1 :(得分:1)

你可以使用

private static String tranPattern(String ori) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
    SimpleDateFormat ouputFormat = new SimpleDateFormat("dd-mm-yyyy");
    return ouputFormat.format(format.parse(ori));
}

答案 2 :(得分:1)

如果输入字符串的格式是固定的,则可以使用replaceAll方法。

String in = "2015-02-12";
//                             +-- match four characters in group 1
//                             |     |+-- - match two characters in group 2
//                           vvvv   vv   vv-- - match two characters in group 3 
String out = in.replaceAll("(....)-(..)-(..)", "$3-$2-$1");
//                                              replace the input string by the 
//                                              matching groups
System.out.println("out = " + out);

如果您使用的是JavaFX DatePicker,可以查看http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/date-picker.htm

答案 3 :(得分:0)

一种可能性是-上的拆分/反向/加入:

package so28360178;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.reverse;
import static java.lang.String.format;

public class App {

    public static final Joiner JOINER = Joiner.on('-');
    public static final Splitter SPLITTER = Splitter.on('-');

    public static void main(final String[] args) {
        // with guava Splitter/Joiner and Lists#reverse
        System.out.println(JOINER.join(reverse(newArrayList(SPLITTER.split("2015-02-12"))))); // 12-02-2015

        // plain old java using String#format for the reverse
        System.out.println(format("%3$s-%2$s-%1$s", "2015-02-12".split("-"))); // 12-02-2015
    }
}
相关问题