How to format a Date in Java ME?

大城市里の小女人 提交于 2019-11-28 10:21:53

问题


So I have a Date object and I want to create a method so that it prints the Date in the 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.


回答1:


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);


来源:https://stackoverflow.com/questions/7364443/how-to-format-a-date-in-java-me

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!