0

这是代码,代码的输出是“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){
             ;
         }

    }
}
4

2 回答 2

0

Date 的格式仅用于显示目的。我们不应该关心运行时如何在内部表示或存储 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)); 
于 2013-06-09T08:37:41.823 回答
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 的数据转换很糟糕。使用乔达时间

于 2013-06-09T08:56:06.420 回答