【问题标题】:Take away a single day using Calendar in Java?在 Java 中使用 Calendar 带走一天?
【发布时间】:2016-03-21 23:46:57
【问题描述】:

我有一个插入 Google Fit Api 并返回过去 7 天的步骤的应用程序,方法如下。正如屏幕截图所示,虽然我希望将这一天添加到步数中。

我尝试了很多选择,一次只带走一天的 7 循环,但没有运气,它只是说在同一天。任何帮助都会非常感谢。

private void dumpDataSet(DataSet dataSet) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getTimeInstance();

    int i = 0;

    for (DataPoint dp : dataSet.getDataPoints()) {

        for(Field field : dp.getDataType().getFields()) { //loop 7 times

            int test = dp.getValue(field).asInt();

            String weekSteps= String.valueOf(test); //get weekday steps one at a time

            SimpleDateFormat sdf = new SimpleDateFormat("EEEE");



            Calendar cal = Calendar.getInstance();
            String weekday = sdf.format(cal.getTime());

            String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day 

            FeedItem item = new FeedItem();
            item.setTitle(weekStepsFinal);

            feedItemList.add(item);

        }
    }

}

顺便说一句,有 7 个数据集。

【问题讨论】:

    标签: java android calendar google-fit


    【解决方案1】:

    如果“一次一天带走”意味着您希望日子倒退,那么方法如下:

    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    
    System.out.println("Last 7 days (starting today):");
    Calendar cal = Calendar.getInstance(); // Initialized to today/now
    for (int i = 0; i < 7; i++) {
        System.out.println("  " + sdf.format(cal.getTime()));
        cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
    }
    

    输出

    Last 7 days (starting today):
      Monday
      Sunday
      Saturday
      Friday
      Thursday
      Wednesday
      Tuesday
    

    【讨论】:

    • 谢谢你改变了升技,但想法是对的 :) 在你的帮助下终于搞定了
    【解决方案2】:

    这将从日历中减去 7 天,得到 7 天前的日期:

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, -7).
    

    【讨论】:

    • 请注意,这将像您希望的那样滚动到前几个月和几年。
    【解决方案3】:

    要减去一天,请使用以下代码:

    int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
    Date currentDate = new Date();
    long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
    
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    String day = sdf.format(previousDay);
    

    【讨论】:

      猜你喜欢
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多