想要在java中更改日期格式

时间:2013-06-09 08:34:34

标签: java

这是代码,代码的输出是“Thu Jun 06 08:00:00 PKT 2013”​​,但我希望格式为2013-06-08 00:00:00,请帮助我

    import java.text.SimpleDateFormat;
  import java.text.ParseException;
   import java.util.*;
   import javax.script.*;
public class time {
    public static void main (String[] args)throws ParseException{
        String date1 = "2013/06/06";
        String time1 = "08:00 AM";
        String time2 = "18:00 PM";
        SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd hh:mm ");
        try{
            Date dateObj1 = sdf.parse(date1 + " " + time1);
            Date dateObj3 = sdf.parse(date1 + " " + time2);
            System.out.println("Date Start: "+dateObj1);
            System.out.println("Date End: "+dateObj3);
            int c=0;
            long dif = dateObj1.getTime();
            while (dif < dateObj3.getTime()) {
                        System.out.println(c++);
                           Date slot = new Date(dif);
                           System.out.println("Hour Slot --->" + slot);
                           dif+=3600000;
             }
             System.out.println("c is :"+c);
         }
         catch(ParseException e){
             ;
         }

    }
}

2 个答案:

答案 0 :(得分:0)

日期的格式仅用于显示目的。我们不应该关心运行时如何在内部表示或存储Date对象。请参阅代码中的注释:

String date1 = "2013/06/06";
String time1 = "08:00 AM";
// You are trying to convert the String "2013/06/06 08:00 AM" to a Date object
// for this you tell the DateFormat that the date string is formatted as
// "yyyy/MM/dd hh:mm a" , so when you parse the String to Date , it is converted to
// a valid and expected Date object.
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm a"); 
Date date = df.parse(date1+" "+time1);        
System.out.println(date); //Thu Jun 06 08:00:00 IST 2013
// To print "2013-06-06 08:00:00"
// You tell SimpleDateFormat to format the date as ""yyyy-MM-dd hh:mm:ss" while 
//printing
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date)); 

答案 1 :(得分:0)

使用此

    String date1 = "2013/06/06";
    String time1 = "08:00 AM";
    String time2 = "18:00 PM";
    SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd hh:mm ");
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyy-MM-dd hh:mm:ss ");
    try{
        Date dateObj1 = sdf.parse(date1 + " " + time1);
        Date dateObj3 = sdf.parse(date1 + " " + time2);
        System.out.println("Date Start: "+sdf1.format(dateObj1));
        System.out.println("Date End: "+sdf1.format(dateObj3));
        int c=0;
        long dif = dateObj1.getTime();
        while (dif < dateObj3.getTime()) {
                    System.out.println(c++);
                       Date slot = new Date(dif);
                       System.out.println("Hour Slot --->" + sdf1.format(slot));
                       dif+=3600000;
         }
         System.out.println("c is :"+c);
     }
     catch(ParseException e){
         ;
     }

我的建议:Java 6的数据转换很糟糕。使用joda时间