【问题标题】:How to change the value of date? [duplicate]如何更改日期的值? [复制]
【发布时间】:2021-10-14 20:16:47
【问题描述】:

我想取今天的日期并将其更改为明天的日期。我会解释:

今天是本月的 14 号。我想自动显示明天的号码(15 号)。我该怎么做?

我尝试将字符串转换为整数,然后添加 1,但我无法运行程序....

package com.example.changetime;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView dateOne = findViewById(R.id.dateOne);
        TextView dateTwo = findViewById(R.id.dateTwo);

        String currentDate = new SimpleDateFormat("dd-MM-yy", Locale.getDefault()).format(new Date());
        dateOne.setText(currentDate);

        String currentDay = new SimpleDateFormat("dd", Locale.getDefault()).format(new Date());
        dateTwo.setText(currentDay); //Here I want to show tomorrow's date

    }
}

感谢您的关注!

【问题讨论】:

  • 考虑扔掉早已过时且臭名昭著的麻烦SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。
  • 在链接的原始问题下,我推荐 the answer by Basil Bourque 使用 java.time。您可能还会发现 the one by catch23 很有趣。

标签: java android


【解决方案1】:

如果您是 Java 8+,则可以使用 java.time 库中的 LocalDateDateTimeFormatter类,而不是 SimpleDateFormat

String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("dd-MM-yy"));
System.out.println(tomorrow);

注意.now() 获取当前日期,.plusDays(1) 添加一天,.formatString 格式化为给定模式。

输出(2021 年 10 月 14 日):

15-10-21

【讨论】:

    猜你喜欢
    • 2015-07-25
    • 2018-03-22
    • 1970-01-01
    • 2014-04-27
    • 2021-01-11
    • 2020-01-27
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多