简体   繁体   English

Java日期和时间转换

[英]Java Date and Time convert

I have this piece of code below: 我在下面有这段代码:

private final static String DATE_TIME_FORMAT_FILE = "dd_MM_YYYY_HH_mm";
private final static String DATE_TIME_FORMAT_DATA = "dd/MM/YYYY HH:mm";

String sdfDateTimeData = null;
    Calendar calData = Calendar.getInstance();
    SimpleDateFormat sdfFile = new SimpleDateFormat(DATE_TIME_FORMAT_FILE);
    SimpleDateFormat sdfData = new SimpleDateFormat(DATE_TIME_FORMAT_DATA);
    String sdfDateTimeFile = sdfFile.format(calData.getTime());

    try {
        Date dt = sdfFile.parse(sdfDateTimeFile);
        sdfDateTimeData = sdfData.format(dt);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

I want to convert same date and time into 2 diferent formats. 我想将相同的日期和时间转换为2种不同的格式。 It runs properly but he 2nd format changes the date: 它可以正常运行,但是第二种格式可以更改日期:

OUTPUT: OUTPUT:

16_06_2014_23_11

29/12/2014 23:11

As you can see the date changes from 16_06_2014 to 29/12/2014. 如您所见,日期从16_06_2014更改为2014年12月29日。 Anyone know why??? 有人知道为什么吗?

Thank you... 谢谢...

The uppercase Y stands for "week year". 大写字母Y代表“星期”。 You need the lowercase y in your format. 您需要使用格式的小写字母y

Here's the javadoc for SimpleDateFormat . 这是SimpleDateFormatjavadoc It shows you how to create your patterns and this is what your patterns should look like: 它向您展示了如何创建模式,这就是模式的外观:

private final static String DATE_TIME_FORMAT_FILE = "dd_MM_yyyy_HH_mm";
private final static String DATE_TIME_FORMAT_DATA = "dd/MM/yyyy HH:mm";

Try using yyyy as: 尝试将yyyy用作:

private final static String DATE_TIME_FORMAT_FILE = "dd_MM_yyyy_HH_mm";
private final static String DATE_TIME_FORMAT_DATA = "dd/MM/yyyy HH:mm";

Instead of dd/MM/ YYYY 代替dd / MM / YYYY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM