【问题标题】:How to create a single Calendar object with a Date object and a string that holds the time. - JAVA如何使用 Date 对象和保存时间的字符串创建单个 Calendar 对象。 - 爪哇
【发布时间】:2017-03-29 22:53:33
【问题描述】:

我目前正在尝试制作一个日历对象。一个函数返回一个包含月、日和年的日期对象。另一个函数返回一个保存时间的字符串对象。

如何使用这两个信息来创建单个日历对象?

我正在使用 Java

谢谢。

【问题讨论】:

    标签: string date


    【解决方案1】:
    import java.text.SimpleDateFormat;
    import java.util.Calender;
    import java.util.Date;
    
    public class Test {
        @SuppressWarnings("deprecation")
        public static void main (String args[]) {
    
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = sdf.parse("2011-03-17");
            // suppose your method return date object like prior line date object.
    
            //now you get time from a method which returns date String like time below: 
            String time = "23:44:33";
            String splitTime[] = time.split(":");
    
            // Now create a single CAlender object containing time and date
    
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DATE, date.getDate());
            calendar.set(Calendar.MONTH, date.getMonth());
            calendar.set(Calendar.YEAR, date.getYear());
            // till this point we have set the date
    
            // now we will set the time
            calendar.set(Calendar.HOUR, Integer.parseInt(splitTime[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(splitTime[1]));
            calendar.set(Calendar.SECOND, Integer.parseInt(splitTime[2]));
    
            System.out.println(sdf1.format(calendar.getTime()));
    
            //You will get the desired result
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
    But 
    Fetching day, month, year from date obbject is Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR/MONTH/DAY). Refer Java Doc for more information.
    
    For year we need to add 1900 in year what we get from d.getYear(). Because it provides year - 1900. Still, deprecated code shouldn't be used. Use Calender class only.
    
    Hope you got your answer !!!!
    

    【讨论】:

      【解决方案2】:

      不要使用旧的麻烦的日期时间类,现在是旧的。使用 java.time 类。

      LocalDate ld = LocalDate.of( 2017 , Month.MAY , 23 );
      LocalTime lt = LocalTime.of( 12 , 23 , 45 );
      

      要以标准 ISO 8601 格式生成表示任一值的字符串,请调用 toString。对于其他格式,请使用DateTimeFormatter

      请在发帖前搜索 Stack Overflow。这已经处理了数百次了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-19
        相关资源
        最近更新 更多