简体   繁体   English

日期格式给出错误的结果

[英]Date Format Gives Wrong Result

I'm trying a code in java to convert a String into Date but I'm getting the output wrong. 我正在尝试使用Java中的代码将String转换为Date,但是输出错误。 Can you please help me out to sort out it. 您能帮我解决一下吗?

Here is my java code 这是我的java代码

import java.text.*;
import java.util.*;

public class My {

public static void main( String[] args ) {

    String textDate = "31/12/2015";
    Date actualDate = null;

    SimpleDateFormat yy = new SimpleDateFormat( "MM/dd/yy" );
    SimpleDateFormat yyyy = new SimpleDateFormat( "MM/dd/yyyy" );

    try {
        actualDate = yy.parse( textDate );
    }
    catch ( ParseException pe ) {
        System.out.println( pe.toString() );
    }

    System.out.print( textDate + " enhanced:  " );
    System.out.println( yyyy.format( actualDate ) );
}
}

Output I got: 我得到的输出:

31/12/2015 enhanced: 07/12/2017 31/12/2015增强:2017年7月12日

The date you are trying to parse is not in Month/Day/2 digit year format.You need something like 您要解析的日期不是Month / Day / 2位数年份格式。您需要类似

SimpleDateFormat yy = new SimpleDateFormat( "dd/MM/yyyy" );

or change the String like 像这样更改String

String textDate = "12/31/15";

Change SimpleDateFormat yy = new SimpleDateFormat( "MM/dd/yy" ); 更改SimpleDateFormat yy = new SimpleDateFormat( "MM/dd/yy" ); to SimpleDateFormat yy = new SimpleDateFormat("dd/MM/yy"); 转换为SimpleDateFormat yy = new SimpleDateFormat("dd/MM/yy");

The sequence of your code is wrong. 您的代码顺序错误。 You cannot parse dd/MM/yyyy to dd/MM/yy , so you have to use yyyy.parse(textDate) at first and use yy.format(actualDate) later to get 31/12/15 . 你不能解析dd/MM/yyyydd/MM/yy ,所以你必须使用yyyy.parse(textDate)在第一和使用yy.format(actualDate)后获得31/12/15

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

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