【问题标题】:How to count down 6 month in android? [duplicate]如何在android中倒计时6个月? [复制]
【发布时间】:2017-07-21 14:25:51
【问题描述】:

我有一个格式为“20161201”的日期字符串。
如何将此日期时间字符串设为july 2016?

我想显示该日期时间字符串之前的 6 个月。
有可能吗?

另外我如何将“20161201”转换为Dec 2016?

【问题讨论】:

    标签: java android datetime


    【解决方案1】:

    您使用以下代码更改格式,

        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

    【讨论】:

    • 这不是倒计时。输入日期前 6 个月
    【解决方案2】:

    对于将“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)

    【讨论】:

    • OP 想从输入日期中减去 6 个月
    • 您可以将您的月份更改为毫秒,然后尝试我的解决方案
    • 6 个月到毫秒是 15778476000
    • 我明白这一点,但您也可以编辑答案以显示从20161201 获取july 2016。这就是我的观点
    • 我编辑了我的答案。试试看
    【解决方案3】:

    如何将此日期时间字符串设为 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
    

    【讨论】:

    • 谢谢兄弟..很好
    猜你喜欢
    • 2012-04-19
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2016-07-21
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多