最近,我开始使用AndroidStudio3.1.2和SDK 19编写我真正的第一个Android项目。
我的一个对象有日期属性。在某些时候,我希望在TextView中显示整个日期、时间或其中的部分。所以我试着用新手的方式,在约会的时候打电话给toString()。但是,显示的文本包含我在用于创建Date对象的SingleDateFormat模式中没有定义的元素。
我是这样在myObject上创建日期的:
Date date1;
Date date2;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = format.parse(json.getString("date_1"));
dtae2 = format.parse(json.getString("date_2"));
} catch(ParseException e) {
//error handling stuff
e.printStackTrace();
}这是我想在视图上显示日期的地方:
myTextView.setText("First appearance logged at " + myObject.getDate1().toString());我预期会显示一个类似2018-08-16 12:14:42的字符串。相反,我得到的是Thu Aug 12:14:42 GMT +02:00 2018。这似乎是另一个DateFormat,忽略了我的自定义模式。
所以我的问题是,如果有一种方法来操作toString()的输出,那么日期就会以我在模式中定义的方式显示出来。我可以以某种方式将模式传递给toString()方法吗?
编辑
我将对象的属性更改为String类型,尽管它更容易显示。把它们转换成约会的原因是,我需要计算出两个人之间的持续时间,但这不是一个我无法解决的问题。多亏了社区。
发布于 2018-08-16 10:27:02
根据您的需要,您只需使用json.getString("date_1")即可。
你不需要设置额外的逻辑。要将String日期转换为Date对象以进行某些计算时,需要进行解析。
如果要更改接收日期的格式,请使用此方法。
changeStringDateFormat(json.getString("date_1"), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");把这个方法放进你的Util。
public String changeStringDateFormat(String date, String inputDateFormat, String outPutDateFormat) {
Date initDate = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
initDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outputFormatter = new SimpleDateFormat(outPutDateFormat);
String parsedDate = outputFormatter.format(initDate);
return parsedDate;
}参见Java日期文件,它从默认格式返回字符串。
公共字符串toString() 将此日期对象转换为窗体的字符串: 陶氏dd hh:mm:ss zzz yyyy
发布于 2018-08-16 10:29:38
只需编写以下代码片段即可。
JAVA文件
public class MainActivity extends AppCompatActivity {
TextView my_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_text = findViewById(R.id.my_text);
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
Toast.makeText(getApplicationContext(), "" + date, Toast.LENGTH_SHORT).show();
my_text.setText("Your Date is : " + date);
}
}XML文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mydemo.com.anew.MainActivity">
<TextView
android:id="@+id/my_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>见产出:

请参见输出截图,与您的需求相同,获取当前日期:

请参阅此教程
希望这对你有帮助
发布于 2018-08-18 21:11:59
tl;dr
使用现代的java.time类,而不是可怕的遗留Date & SimpleDateFormat类。
myJavaUtilDate // Never use `java.util.Date`.
.toInstant() // Convert from legacy class to modern replacement. Returns a `Instant` object, a moment in UTC.
.atOffset( // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
ZoneOffset.UTC // Constant defining an offset-from-UTC of zero, UTC itself.
) // Returns a `OffsetDateTime` object.
.format( // Generate a `String` with text representing the value of this `OffsetDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // Pre-defined formatter stored in this constant.
) // Returns a `String` object.
.replace( "T" , " " ) // Replace the standard `T` in the middle with your desired SPACE character.2018-08-16 10:14:42
java.time
您使用的是几年前被java.time类取代的可怕的旧类。
如果传递一个java.util.Date对象,则立即转换为java.time.Instant。这两者都代表了世界协调时的一个时刻。Instant的分辨率为纳秒而非毫秒。
若要在旧类和现代类之间进行转换,请查看添加到旧类的新转换方法。
Instant
Instant instant = myJavaUtilDate.toInstant() ; // New method on old class for converting to/from java.time classes.ISO 8601
若要生成具有与所需格式类似的标准ISO 8601格式的文本的ISO 8601,请调用toString。
String output = instant.toString() ; // Generate text in standard ISO 8601 format.运行时间= Duration
顺便说一下,要计算经过的时间,请使用Duration类。传递一对Instant对象,以计算24小时“天”、小时、分钟和秒的时间。
Duration d = Duration.between( start , stop ) ; // Calc elapsed time.2018-08-16T10:14:42Z
OffsetDateTime
对于其他格式,从基本的Instant类转换为更灵活的OffsetDateTime类。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;odt.toString():2018-08-16T10:14:42 Z
DateTimeFormatter
所需格式接近预定义的格式化程序DateTimeFormatter.ISO_LOCAL_DATE_TIME。只需用空格替换中间的T即可。
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;2018-08-16 10:14:42
ZonedDateTime
请记住,到目前为止,我们只关注世界协调时。在任何一个特定的时刻,日期和时间在全球各地都是不同的.
如果您想通过某个区域(时区)的人使用的挂钟时间的镜头看到相同的时刻,那么应用一个ZoneId来获得一个ZonedDateTime对象。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;zdt.toString():2018-08-16T11:14:42+01:00非洲/突尼斯
您可以使用上面看到的相同的格式化程序生成所需格式的字符串。
String output = zdt.format( f ) ;关于java.time
http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html框架内置到Java8和更高版本中。这些类取代了麻烦的旧遗赠日期时间类,如java.util.Date、Calendar和SimpleDateFormat。
http://www.joda.org/joda-time/项目现在在维护模式中,建议迁移到java.time类。
要了解更多信息,请参见http://docs.oracle.com/javase/tutorial/datetime/TOC.html。并搜索堆栈溢出以获得许多示例和解释。规范是JSR 310。
您可以直接与数据库交换java.time对象。使用与JDBC 4.2或更高版本兼容的JDBC 4.2。不需要字符串,也不需要java.sql.*类。
在哪里获得java.time类?
三次-额外项目使用其他类扩展java.time。这个项目是将来可能加入java.time的试验场。您可以在这里找到一些有用的类,如Interval、YearWeek、YearQuarter和更多。
https://stackoverflow.com/questions/51874735
复制相似问题