How to format a Date in Java ME?

后端 未结 1 1539
忘掉有多难
忘掉有多难 2020-12-22 01:54

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

相关标签:
1条回答
  • 2020-12-22 02:14

    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 讨论(0)
提交回复
热议问题