编程知识 cdmana.com

Getting started with Java lesson 105 -- swapping dates represented by date with dates represented by calendar

There are so many on the Internet java The article , Why it depends on my ?

The system is comprehensive : One article in the East and one in the West , I feel dizzy . Just follow my route , You can't find me .

It's not easy to code words , Please pay attention to the official account. , forward , give the thumbs-up , Just move your fingers , Return video , Just to achieve you !

problem

     On the basis of the previous case , send Date The date and Calendar The indicated date is exchanged .

programme

     First , Use Calendar Class getInstance Method to get the current date - Time calendar; then , Instantiation Date class , Get the current date represented - Time object date; Last , First , Use Calendar Of setTime Methods will Date Object to Calendar object , then , Use Calendar Object's getTime Method Calendar The representation object is converted to Date object .

step

Step one : Build test methods

     First , stay TestCalendar Class to add test methods testSetTimeAndGetTime; then , Use Calendar Class getInstance Method to get the current date - Time calendar; Last , Instantiation Date class , Get the current date represented - Time object date, The code is as follows :

    package day03;
    
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import org.junit.Test;
    
    public class TestCalendar{
     
     /**
      * Use Date The date and Calendar The indicated date is exchanged 
      */
      @Test
      public void testSetTimeAndGetTime(){
          Calendar calendar=Calendar.getInstance();
          Date date=new Date();
      }
    
    }

Step two : Use setTime Method

     First , Use Calendar Of setTime Methods will Date Object to Calendar object , then , Use Calendar Object's getTime Method Calendar The representation object is converted to Date object , The code is as follows :

    package day03;
    
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import org.junit.Test;
    
    public class TestCalendar{
     
     /**
      * Use Date The date and Calendar The indicated date is exchanged 
      */
      @Test
      public void testSetTimeAndGetTime(){
          Calendar calendar=Calendar.getInstance();
          Date date=new Date();
          
          calendar.setTime(date);// take Date Convert to Calendar
          date=calendar.getTime();// take Calendar Convert to Date
      }
    
    }

 

Official account , Get a learning video

版权声明
本文为[Monkeys learn to program]所创,转载请带上原文链接,感谢

Scroll to Top