编程知识 cdmana.com

Getting started with Java lesson 99 -- parsing strings to dates when using the parse method

It's not easy to code words , Please pay attention to the official account. , forward , give the thumbs-up , Just move your fingers , No money , Thank you, old fellow. !

problem

     On the basis of the previous case , Date represented by string "2013-12-25" Convert to Date Date represented by type .

programme

    1) Instantiation SimpleDateFormat Class object , This class enables users to select a custom date - Time format mode , The code is as follows :

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

     In the above code , Set date - The time format is "yyyy-MM-dd", This is because , The time format we want to convert "2013-13-25" Want to be with SimpleDateFormat Constructed format match , Before conversion .

    2) call SimpleDateFormat Class parse Method , Convert date string to Date Class object , The code is as follows :

Date date=sdf.parse(str);

step

     To implement this case, follow the steps below .

Step one : Build test methods and SimpleDateFormat Class object

     First , stay TestSimpleDateFormat New test method in class testParse; then , Instantiation SimpleDateFormat Class object , This class enables users to select a custom date - Time format mode , The code is as follows :

    package day03;
    
    import java.text.SimpleDate;
    import java.util.Date;
    import org.junit.Test;
    
    public class TestSimpleDateFormat{
        
        /**
         * test parse Method 
         */
         @Test
         public void testParse() throws Exception{
             String str="2013-12-25";
             SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
         }
    }

     Please note that , Here, SimpleDateFormat The date format of the construction should be the same as the string str Date format to match .

Step two : Convert date string to Date Class object

     call SimpleDateFormat Class parse Method , Convert date string to Date Class object , The code is as follows :

    package day03;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.junit.Test;
    
    public class TestSimpleDateFormat{
     /**
      * test parse Method 
      */
      @Test
      public void testParse() throws Exception{
          String str="2013-12-25";
          SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
          
          Date date=sdf.parse(str);
          System.out.println(date);
      }   
    }

Step three : function

     function testParse Method , The console output is as follows :

    Wed Dec 25 00:00:00 CST 2013

     View output , Can be the date output in the default time format - Time .

Official account , Get a learning video

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

Scroll to Top