【发布时间】:2017-07-21 14:25:51
【问题描述】:
我有一个格式为“20161201”的日期字符串。
如何将此日期时间字符串设为july 2016?
我想显示该日期时间字符串之前的 6 个月。
有可能吗?
另外我如何将“20161201”转换为Dec 2016?
【问题讨论】:
我有一个格式为“20161201”的日期字符串。
如何将此日期时间字符串设为july 2016?
我想显示该日期时间字符串之前的 6 个月。
有可能吗?
另外我如何将“20161201”转换为Dec 2016?
【问题讨论】:
您使用以下代码更改格式,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
SimpleDateFormat expectedSDF = new SimpleDateFormat("MMMM yyyy", Locale.getDefault());
Date date = simpleDateFormat.parse(dateString);
String newFormatString = expectedSDF.format(date);
对于倒计时,使用 CountDownTimer
https://developer.android.com/reference/android/os/CountDownTimer.html
【讨论】:
对于将“20161201”转换为“2016 年 12 月”:
//Convert string to date
String dateString = "20161201";
SimpleDateFormat parseDateFormat = new SimpleDateFormat("yyyyMMdd");
Date convertedDate = new Date();
try {
convertedDate = parseDateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
//Convert date to string
SimpleDateFormat outputDateFormat = new SimpleDateFormat("MMM yyyy");
String result = outputDateFormat.format(convertedDate);
//Print the result
System.out.println(result);
在'6个月'到毫秒是15778476000。您可以通过使用以毫秒为单位获取6个月后的日期
long resultdate = convertedDate.getTime() - 15778476000L;
然后
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(resultdate);
String result = outputDateFormat.format(calendar.getTime());
得到结果
https://developer.android.com/reference/java/text/SimpleDateFormat.html https://developer.android.com/reference/java/util/Date.html https://developer.android.com/reference/java/util/Calendar.html#setTimeInMillis(long)
【讨论】:
20161201 获取july 2016。这就是我的观点
如何将此日期时间字符串设为 2016 年 7 月
我想显示该日期时间字符串之前的 6 个月
七月是五个月……
这是 6 个月的答案
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyyMMdd").parse("20161201"));
c.set(Calendar.MONTH, c.get(Calendar.MONTH)-6);
String output = new SimpleDateFormat("MMMM yyyy").format(c.getTime()));
// June 2016
【讨论】: