Java already provides powerful functions in dealing with Date (also Time) problems.
So you can input a String (i.e. “
2001.07.04 AD at 12:08:56 PDT
”), and get the Date Object by Java Methods.
In contrast, you can also provide a Date Object (or long number, etc.), and print the date as required date format easily.
What you need to done is just define the format String, i.e. “yyyy-mm-dd HH:mm:ss”.
(Pay attention to the capticals, because they mean different format).
Here is a simple demostration.
Reference Codeimport java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import junit.framework.TestCase;
public class DateFormatTest extends TestCase {
private final static String date1 = "2011-10-10 22:12:34";
private final static long dateLong1 = Long.parseLong("1318252354000");
private static DateFormat formatter1 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
private final static String date2 = "AM 12:34:56 04/09/85 JST";
private final static long dateLong2 = Long.parseLong("481822496000");
private static DateFormat formatter2 = new SimpleDateFormat(
"aa hh:mm:ss MM/dd/yy zzz", Locale.ENGLISH);
public void test1() throws ParseException {
long dateLong = formatter1.parse(date1).getTime();
System.out.println(this.getName() + ": Long Number is " + dateLong);
assertEquals(dateLong1, dateLong);
}
public void test2() throws ParseException {
String dateString = formatter1.format(new Date(dateLong1));
System.out.println(this.getName() + ": Formatted Date String is "
+ dateString);
assertEquals(date1, dateString);
}
public void test3() throws ParseException {
long dateLong = formatter2.parse(date2).getTime();
System.out.println(this.getName() + ": Long Number is " + dateLong);
assertEquals(dateLong2, dateLong);
}
public void test4() throws ParseException {
String dateString = formatter2.format(new Date(dateLong2));
System.out.println(this.getName() + ": Formatted Date String is "
+ dateString);
assertEquals(date2, dateString);
}
}
The Output Result is :
test1: Long Number is 1318252354000
test2: Formatted Date String is 2011-10-10 22:12:34
test3: Long Number is 481822496000
test4: Formatted Date String is AM 12:34:56 04/09/85 JST
From Javadoc of JDK, we can easily learn how to write the format String.
Be careful on how to control the length of the items: i.e. the “yy” means here display the year, and two digits will be displayed.
Also, the “/” or “-” (or others) which are not defined in the table, will mean the separator.
没有评论:
发表评论