Monday, April 17, 2006

Getting and Playing with Date in Java

Many people have been finding it difficult to format dates and have been creating parsers to format date strings.This post unleashes how a java inbuilt mechanism can be used to format date


/*
* ShowToday.java
*
* Created on March 31, 2006, 2:06 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package learning;

/**
*
* @author AshwinK
*/
import java.util.*;
import java.text.*;

public class GetToday {
public static void main(String args[]) {
GetToday gt = new GetToday();
gt.test();
}
public void test() {
System.out.println(testDateFormat("dd MMMMM yyyy"));
System.out.println(testDateFormat("yyyyMMdd"));
System.out.println(testDateFormat("dd.MM.yy"));
System.out.println(testDateFormat("MM/dd/yy"));
System.out.println(testDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(testDateFormat("EEE, MMM d, ''yy"));
System.out.println(testDateFormat("h:mm a"));
System.out.println(testDateFormat("H:mm:ss:SSS"));
System.out.println(testDateFormat("K:mm a,z"));
System.out.println(testDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa"));
}

public String testDateFormat (String format) {
Date today = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(format);
String datenewformat = formatter.format(today);
return datenewformat;
}
}


Java assign's each alphabet to corresponding date part for example

y -- Year
M -- Month
d -- Day
h -- Hour
m -- Minute
s -- Second

if we give format as yyyymmddhhmmss and date is 2005-04-12 12:12:12

output would be like 20050412121212

If any doubt's mail me at ashwin.rayaprolu@gmail.com

No comments: