Tuesday 4 July 2017

Java8: Convert String To Integer and To Date

Java 8, string to integer, string to date, convert  date to different formats




package convert;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;

public class ConvertStringToIntAndToDate {

       public static void main(String[] args){

              // E.g. Integer.parseInt(), this converts to integer

              String number = "50";
              int result = Integer.parseInt(number);
              System.out.println("1.The string which is coonverted to int is : " + result);


              // E.g. Integer.valueOf(), this will return an integer object

              String number1 = "20";
              Integer result1 = Integer.valueOf(number1);
              System.out.println("2. The string which is converted to an integer object: " + result1);

           

              // Converts String to Date Format which is like Thu Dec 31 00:00:00 IST 1998

              try{

                     stringToDate ("July 03, 2017", "MMMM dd, yyyy");
                     stringToDate("31/12/2016", "dd/MM/yyyy");
                     stringToDate("12 31, 2000", "MM dd, yyyy");
                     stringToDate("Tue, jul 31 2017", "E, MMM dd yyyy");
                     stringToDate("Tue, jul 31 2017 23:37:50", "E, MMM dd yyyy HH:mm:ss");
                     stringToDate("30-jun-2017 23:37:50", "dd-MMM-yyyy HH:mm:ss");

              } catch (Exception e) {

                     System.out.println(e.getStackTrace());

              }

              // Convert date to different formats

              convertDatetoDiffFormat();

       }

     



    public static void stringToDate(String dateString,String dateFormat) throws ParseException{

       // Java 8 update

       DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
       Date date = format.parse(dateString);
       System.out.println("String is converted to date: "+date);

     

    }


    public static void convertDatetoDiffFormat(){

       String format1=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date());
       System.out.println(format1);

    }



}









Output:



1.The string which is converted to INT is : 50

2. The string which is converted to an integer object: 20

String is converted to date: Mon Jul 03 00:00:00 IST 2017

String is converted to date: Sat Dec 31 00:00:00 IST 2016

String is converted to date: Sun Dec 31 00:00:00 IST 2000

String is converted to date: Mon Jul 31 00:00:00 IST 2017

String is converted to date: Mon Jul 31 23:37:50 IST 2017

String is converted to date: Fri Jun 30 23:37:50 IST 2017

Mon Jul 03 16:06:31 IST 2017

2017-07-03 16:06:32.011

No comments:

Post a Comment