开发者

How to format a Date in Java ME?

So I have a Date object and I want to create a method so that it prints the Date in the 开发者_Python百科following format:

11 September 2011, 9:15pm

How do I do that? As of now I am just doing a toString to the date and it gives me all the GMT information and seconds precision that I don't need. Do I have to use a DateFormatter or is there an easier way to do this?

This was edited to include Java ME in the title and the tags after some of the answers that were correct for the original question were posted.


You may use SimpleDateFormat class to format your date. http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html

I guess the pattern would be something like this:

SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy, h:ma");
format.format(yourDate);

EDIT for Java ME; I read that there is no SimpleDateFormat class in Java ME specs. So I would try Calendar;

First put your date to the Calendar, then get all you need. Better is make this a method

Calendar calendar = Calendar.getInstance();
Date myDate = new Date(); // as an example, date of "now"
calendar.setTime(myDate);

int day = calendar.get(Calendar.DAY_OF_MONTH);
int monthNumber = calendar.get(Calendar.MONTH);

String[] _months = new DateFormatSymbols().getMonths();
String[] months = new String[12];
for(int i =0; i < 12; i++){
    months[i] = _months[i];
}
//because there is something wrong, we have a 12. month in the name of "" (nothing)

//or if there is no DateFormatSymbols class in your plans
//you may write for yourself;
/*
String[] monthNames = {"January", "February",
            "March", "April", "May", "June", "July",
            "August", "September", "October", "November",
            "December"};
*/
String month = months[monthNumber]; //or String month = monthNames[monthNumber];

int year = calendar.get(Calendar.YEAR);

int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
String amPm = calendar.get(Calendar.AM_PM)==1 ? "am" : "pm";
System.out.println(day + " " + month + " " + 
    year + ", " + hour + ":" + minute + amPm);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜