【发布时间】:2010-10-02 01:03:34
【问题描述】:
当有年月日时分时,如何根据设备配置日期和时间正确格式化?
【问题讨论】:
标签: android date time formatting format
当有年月日时分时,如何根据设备配置日期和时间正确格式化?
【问题讨论】:
标签: android date time formatting format
使用标准的 Java DateFormat 类。
例如,要显示当前日期和时间,请执行以下操作:
Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
您可以使用自己的值初始化 Date 对象,但是您应该知道构造函数已被弃用,您应该真正使用 Java Calendar 对象。
【讨论】:
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext()); 返回的 dateFormat 类型为 java.text.DateFormat(而不是 android.text.format.DateFormat)
在我看来,android.text.format.DateFormat.getDateFormat(context) 让我感到困惑,因为此方法返回 java.text.DateFormat 而不是 android.text.format.DateFormat - -"。
所以,我使用下面的片段代码以我的格式获取当前日期/时间。
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
or
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());
此外,您还可以使用其他格式。关注DateFormat。
【讨论】:
hh:mm:ss 会在下午 1 点给你01:00:00,你需要使用kk:mm:ss 来获得13:00:00
k 是一天中的小时(1-24),你不是说H,它是一天中的小时(0-23),例如。 HH:mm:ss?见:developer.android.com/reference/java/text/SimpleDateFormat.html
java.text.SimpleDateFormat(您链接的内容并在 0-23 范围内使用 H)和 android.text.format.DateFormat(答案是关于并使用 @987654336 @ 表示 0-23 范围内的小时数)
k 是正确的,但是DateFormat 的文档明确指出有关格式字符串的规范文档,请参阅 SimpleDateFormat。 非常令人困惑。还是我错过了什么?
您可以使用DateFormat。结果取决于手机的默认语言环境,但您也可以指定语言环境:
https://developer.android.com/reference/java/text/DateFormat.html
这是一个结果
DateFormat.getDateInstance().format(date)
法国地区:11 月 3 日。 2017
美国/英语语言环境:1952 年 1 月 12 日
DateFormat.getDateInstance(DateFormat.SHORT).format(date)
法国地区:2017 年 3 月 11 日
美国/英语区域设置:12.13.52
DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)
法国地区:11 月 3 日。 2017
美国/英语语言环境:1952 年 1 月 12 日
DateFormat.getDateInstance(DateFormat.LONG).format(date)
法国地区:2017 年 11 月 3 日
美国/英语语言环境:1952 年 1 月 12 日
DateFormat.getDateInstance(DateFormat.FULL).format(date)
法国地区:vendredi 2017 年 11 月 3 日
美国/英语语言环境:1952 年 4 月 12 日,星期二
DateFormat.getDateTimeInstance().format(date)
法国地区:11 月 3 日。 2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)
法国地区:03/11/2017 16:04
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)
法国地区:03/11/2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)
法国地区:2017 年 3 月 11 日 16:04:58 GMT+01:00
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)
法国地区:03/11/2017 16:04:58 heure normale d'Europe centrale
DateFormat.getTimeInstance().format(date)
法国地区:16:04:58
DateFormat.getTimeInstance(DateFormat.SHORT).format(date)
法国地区:16:04
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)
法国地区:16:04:58
DateFormat.getTimeInstance(DateFormat.LONG).format(date)
法国地区:16:04:58 GMT+01:00
DateFormat.getTimeInstance(DateFormat.FULL).format(date)
法国地区:16:04:58 heure normale d'Europe centrale
【讨论】:
日期到语言环境日期字符串:
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
选项:
DateFormat.getDateInstance()
-> 1969 年 12 月 31 日
DateFormat.getDateTimeInstance()
-> 1969 年 12 月 31 日下午 4:00:00
DateFormat.getTimeInstance()
-> 下午 4:00:00
【讨论】:
这样就可以了:
Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
【讨论】:
使用 SimpleDateFormat
像这样:
event.putExtra("starttime", "12/18/2012");
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));
【讨论】:
new SimpleDateFormat("my-format", Locale.getDefault());
关注这个:http://developer.android.com/reference/android/text/format/Time.html
最好使用Android原生的Time类:
Time now = new Time();
now.setToNow();
然后格式化:
Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));
【讨论】:
这是最简单的方法:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);
String time = df.format(new Date());
如果您正在寻找模式,请检查此 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
【讨论】:
使用这两个作为类变量:
public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
private Calendar mDate = null;
并像这样使用它:
mDate = Calendar.getInstance();
mDate.set(year,months,day);
dateFormat.format(mDate.getTime());
【讨论】:
EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )
【讨论】:
这是我的方法,你可以定义输入输出格式。
public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
inputFormat = "yyyy-MM-dd hh:mm:ss";
}
if(outputFormat.equals("")){
outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
}
Date parsed = null;
String outputDate = "";
SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());
// You can set a different Locale, This example set a locale of Country Mexico.
//SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
//SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));
try {
parsed = df_input.parse(inputDate);
outputDate = df_output.format(parsed);
} catch (Exception e) {
Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
}
return outputDate;
}
【讨论】:
我使用 SimpleDateFormat 无自定义模式以设备预选格式从系统获取实际日期和时间:
public static String getFormattedDate() {
//SimpleDateFormat called without pattern
return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}
返回:
【讨论】:
在 Time 类中使用构建!
Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
【讨论】:
这段代码对我有用!
Date d = new Date();
CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();
【讨论】:
最短路径:
// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())
%tR是%tH:%tM的缩写,<表示重用最后一个参数(1$)。
相当于String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())
https://developer.android.com/reference/java/util/Formatter.html
【讨论】:
String.format("%1tY-%<tm-%<td %<tR", Calendar.getInstance())
日期格式类使用作弊码生成日期。喜欢
你可以查看更多秘籍here。
【讨论】:
其他答案通常是正确的。我想贡献现代答案。大多数其他答案中使用的Date、DateFormat 和SimpleDateFormat 类早已过时,多年来给许多程序员带来了麻烦。今天,我们在java.time,AKA JSR-310,现代 Java 日期和时间 API 方面有了更好的表现。你可以在Android上使用它吗?最肯定!在 ThreeTenABP 项目中,现代类已被反向移植到 Android。详情请见this question: How to use ThreeTenABP in Android Project。
这个 sn-p 应该让你开始:
int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(dateTime.format(formatter));
当我将计算机的首选语言设置为美国英语或英国英语时,会打印:
Sep 28, 2017 10:45:00 PM
当我将其设置为丹麦语时,我得到:
28-09-2017 22:45:00
所以它确实遵循配置。不过,我不确定它遵循您设备的日期和时间设置的具体细节,这可能因手机而异。
【讨论】:
此代码将返回当前日期和时间:
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
【讨论】:
要从毫秒获取区域设置格式的日期或时间,我使用了这个:
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
dateFormat.format(date);
Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);
您可以使用其他日期样式和时间样式。有关样式的更多信息here。
【讨论】:
我是这样使用的:
public class DateUtils {
static DateUtils instance;
private final DateFormat dateFormat;
private final DateFormat timeFormat;
private DateUtils() {
dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
}
public static DateUtils getInstance() {
if (instance == null) {
instance = new DateUtils();
}
return instance;
}
public synchronized static String formatDateTime(long timestamp) {
long milliseconds = timestamp * 1000;
Date dateTime = new Date(milliseconds);
String date = getInstance().dateFormat.format(dateTime);
String time = getInstance().timeFormat.format(dateTime);
return date + " " + time;
}
}
【讨论】:
试试:
event.putExtra("startTime", "10/05/2012");
当您访问传递的变量时:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));
【讨论】:
Java(和 Android)中的 Java.util.Date 和 .Calendar 和 SimpleDateFormat 是出了名的麻烦。避开他们。它们非常糟糕,以至于 Sun/Oracle 放弃了它们,用 Java 8 中的新 java.time 包取代了它们(截至 2014 年在 Android 中没有)。新的java.time 的灵感来自Joda-Time 库。
Joda-Time 确实适用于 Android。
在 StackOverflow 中搜索“Joda”以找到许多示例和讨论。
使用 Joda-Time 2.4 的源代码花絮。
标准格式。
String output = DateTime.now().toString();
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.
本地化格式。
String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() );
// Full (long) format localized for this user's language and culture.
【讨论】:
回到2016年,当我想自定义格式(不是根据设备配置,如你所问...)我通常使用字符串资源文件:
在strings.xml中:
<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>
活动中:
Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));
这对于新的Date Binding Library 的发布也很有用。
所以我可以在布局文件中有这样的东西:
<TextView
android:id="@+id/text_release_date"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="2dp"
android:text="@{@string/myDateFormat(vm.releaseDate)}"
tools:text="0000"
/>
在java类中:
MovieDetailViewModel vm = new MovieDetailViewModel();
vm.setReleaseDate(new Date());
【讨论】:
android Time 类提供3种格式化方法http://developer.android.com/reference/android/text/format/Time.html
我就是这样做的:
/**
* This method will format the data from the android Time class (eg. myTime.setToNow()) into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
String fullTime= "";
String[] sa = new String[2];
if(time.length()>1)
{
Time t = new Time(Time.getCurrentTimezone());
t.parse(time);
// or t.setToNow();
String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
int x = 0;
for(String s : formattedTime.split("\\s",2))
{
System.out.println("Value = " + s);
sa[x] = s;
x++;
}
fullTime = "Date: " + sa[0] + " Time: " + sa[1];
}
else{
fullTime = "No time data";
}
return fullTime;
}
希望对你有帮助:-)
【讨论】:
为时已晚,但可能对某人有所帮助
DateFormat.format(format, timeInMillis);
这里format是你需要的格式
例如:“HH:mm”返回 15:30
【讨论】: