Sep 132011
 

In this post I will share some frequently use methods for Date/Time processing. These methods are needed for almost every project or project starters. Feel free to use and add more features to my class.

First are some Date Time Formatter like date formatter, 24h time formatter, 24h date time formatter…

public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
public static final SimpleDateFormat monthYearFormater = new SimpleDateFormat("MM/yyyy");
public static final SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm:ss");
public static final SimpleDateFormat datetimeFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static final SimpleDateFormat datetimeFormatterNoSecond = new SimpleDateFormat("dd/MM/yyyy HH:mm");
public static final SimpleDateFormat hourMinuteFormater = new SimpleDateFormat("HH:mm");
public static final SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

You will use these formatters to parse String into Date so that you can use for calculation. Or you can use these formatters to format a Date into String so that you can use it to print out a console or notify user via a message.

Next is methods needed to get a Calendar instance, to operate with Date object, you definitely will need Calendar object.

public static Calendar getCalendar(Date date) {
	Calendar c = Calendar.getInstance();
	c.setTime(date);
	return c;
}

public static Calendar getCalendar() {
	Calendar c = Calendar.getInstance();
	c.setTime(new Date());
	return c;
}

Now what if you know date/month/year and want to have a Date object? The following methods will help you to build Date

	/**
	 * Build Date from date/month/year. Zero-based for Month (0=January).
	 * 
	 * @return
	 */
	public static Date buildDate(int year, int month, int date) {
		Calendar calendar = getCalendar();
		calendar.set(year, month, date);
		return calendar.getTime();
	}

	/**
	 * Build Datetime from date/month/year/hour/minute/second. Zero-based for
	 * Month (0=January).
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public static Date buildDateTime(int year, int month, int date, int hour, int minute, int second) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date, hour, minute, second);
		return calendar.getTime();
	}

Sometime you will also need to remove the Time part from a Datetime object, here is the method for that purpose

	/**
	 * Delete time from Date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date) {		
		if (date == null) {
			return null;
		}

		// Obtain an instance of the Calendar.
		Calendar calendar = getCalendar(date);

		// Mark no automatic correction
		calendar.setLenient(false);

		// Remove the hours, minutes, seconds and milliseconds.
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		// Return the date again.
		return calendar.getTime();
	}

And not only to build a new Date object, you can use the following methods to adjust date, like get the previous date or get the next date or get yesterday or get tomorrow date

Continue reading »

Aug 172011
 
Java String split

Split is one of the most use methods of Java String to split a string to match a certain regular expression. Observe the following example:

package net.searchdaily.java.string.common;

/**
 * This is an indepth-example of Java String to demonstrate all features of this
 * class. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class StringSplitExample {
	public static void main(String args[]) {

		/* String to split. */
		String str = "java-string-to-split";
		String[] tempString;

		// delimiter
		String delimiter = "-";
		// given string will be split.
		tempString = str.split(delimiter);
		// print the result
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

		/*
		 * ATTENTION : Some special characters need to be escaped while
		 * providing them as delimiters like "." and "|".
		 */

		System.out.println("");
		str = "java.string.to.split";
		delimiter = ".";
		tempString = str.split(delimiter);
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

		// The second parameter of the split method can help to determine the
		// number of maximum elements to split.

		System.out.println("");
		tempString = str.split(delimiter, 3);
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

	}
}

As you can guess, here is the final result:

image thumb46 Java String common uses

Java String to Int

There are several ways to convert from a String to Integer, the first and most use is to use Integer.parseInt() method from the Integer class.

package net.searchdaily.java.string.common;

/**
 * Convert Java String into Integer. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class StringToInt {

	public static void main(String[] args) {
		String stringText = "2011";
		int intVar = 0;
		try {
			intVar = Integer.parseInt(stringText);
		} catch (NumberFormatException nfe) {
			System.out.println("NumberFormatException: " + nfe.getMessage());
		}
		// now do some integer operation
		intVar++;
		System.out.println(intVar);
	}

}

Yes the result of the above conversion is 2012, but please remember to catch the exception because the parseInt() method will throw some NumberFormatException if the stringText is not a well-numeric-format.

Continue reading »

Aug 142011
 

Java String is widely used in Java application development to store data. An integer, a float point number, a character, a date, an array…all can be represented by a String. So it’s really importance if you study all thing related to Java String and best practice when using it.

1. Java String is immutable.

This means the String object is read-only when the object has been created. You cannot change it anymore.

String string1 = "Hello World this is Java String, it cannot be changed after created";
2. Java String literal is a reference to a String object

This means you can call method of Java String class with a String literal like below:

int strLength = "Java String".length();
3. String concatenate

You can concat Java String like I do below:

String result = "Java" + "String" + "is" + "Immutable";

But the problem is that Java String is Immutable, that mean when you concatenate like above, new String object will be created for each + operator. “Java” is an object and “String” is another object, if “Java” + “String” then it generate another object equals to “Java String”…and this continues if there are more plus (+) operators.

So what is the best practice here? Use StringBuilder instead (you may hear of StringBuffer but I don’t recommend you to use it, maybe I will show why later). OK you should concatenate String as below:

Continue reading »