Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

How to split string literal using java regex

Some time we need to split a string literal based on some delimiters . Java regular expressions provides an easy way of doing it. Let see a sample java program used to split a string literal based on pre-defined delimiter.

MySplitter.java


import java.util.regex.*;

public class MySplitter {
       public static void main(String[] args) {
              String input = "www.naeemgik.blogspot.com";
              Pattern p = Pattern.compile("\\.");
              String pieces[] = p.split(input);
              for (int i = 0; i < pieces.length; i++) {
                     System.out.println(pieces[i]);
              }
       }
}




The output of above code would be:

   www
   naeemgik
   blogspot
   com

 

Date to String conversion in Java

In this post I am going to show you some sample code for converting date to String, getting current date and converting it to specified date format like YYYY-MM-DD, YYYYMMDD and many more format as you wish.

Getting Current Date and display it in yyyy-mm-dd format

public String getCurrentDate() 
{
       String currentDate = "";
       Date d1 = null;
       final Calendar c = Calendar.getInstance();
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

       mYear = c.get(Calendar.YEAR);
       mMonth = c.get(Calendar.MONTH) + 1;
       mDay = c.get(Calendar.DAY_OF_MONTH);
       currentDate = "" + mYear + "-" + mMonth + "-" + mDay + "";
       try {
              d1 = dateFormat.parse(currentDate);
       } catch (ParseException e) {
              e.printStackTrace();
       }

       return dateFormat.format(d1);
}



Getting Date as a parameter and converting it to specified format 

public String getFormtedDate(String date) {

       String myDate = "";
       Date d1 = null;
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

       myDate = date;
       try {
              d1 = dateFormat.parse(myDate);
       } catch (ParseException e) {
              e.printStackTrace();
       }

       return dateFormat.format(d1);
}