如何在Java ME中格式化日期? [英] How to format a Date in Java ME?

查看:76
本文介绍了如何在Java ME中格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个Date对象,我想创建一个方法,以便它以以下格式打印Date:

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

我该怎么做? 到目前为止,我只是对日期执行toString,它为我提供了我不需要的所有GMT信息和秒精度.我必须使用DateFormatter还是有更简单的方法来做到这一点?

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?

经过编辑,标题中包括Java ME,并在一些对原始问题正确的答案后张贴了标签.

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.

推荐答案

您可以使用SimpleDateFormat类格式化日期. http://download.oracle.com/javase /1,5.0/docs/api/java/text/SimpleDateFormat.html

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

我想模式将是这样的:

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

编辑Java ME; 我读到Java ME规范中没有SimpleDateFormat类.所以我会尝试日历;

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

这篇关于如何在Java ME中格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆