Home > Software design >  Need to convert Date Time Format from JSON to 1 day ago or 3 mins ago in Java
Need to convert Date Time Format from JSON to 1 day ago or 3 mins ago in Java

Time:10-08

I need help converting time from the JSON array and displaying it on recycler view in the example published 3 mins ago. The JSON property is "published_on": 1663222879.

My JSON Response:

{
  "Data": [
    {
      "id": "28035611",
      "guid": "https://coingape.com/?p=121674",
      "published_on": 1663222879,
      "imageurl": "https://images.cryptocompare.com/news/default/coingape.png",
      "lang": "EN",
      "source_info": {
        "name": "CoinGape",
        "lang": "EN",
        "img": "https://images.cryptocompare.com/news/default/coingape.png"
      }
    }
],
  "RateLimit": {},
  "HasWarning": false
}

My bindonviewHolder

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.title.setText(dataList.get(position).getTitle());
    holder.body.setText(dataList.get(position).getBody());

    //Glide Library to display the images

    Glide.with(mContext)
            .load(dataList.get(position).getImageurl())
            .into(holder.imageViewUrl);
}

CodePudding user response:

If you want to adjust the date by 1 day back subtract 86400000 from 1665223725508 which is 08/10/2022 for 3 minutes subtract 180000

CodePudding user response:

The value of published_on represents Epoch seconds which can be converted into Instant using Instant#ofEpochSecond.

Once you have the instance of Instant, you can subtract the desired amount of time and also convert the same Epoch seconds as shown below:

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        // Convert the given epoch seconds into Instant
        Instant instant = Instant.ofEpochSecond(1663222879);
        System.out.println(instant);

        // Three minutes ago
        Instant threeMinsAgo = instant.minus(3, ChronoUnit.MINUTES);
        System.out.println(threeMinsAgo);
        long epochSecondThreeMinsAgo = TimeUnit.SECONDS.convert(threeMinsAgo.toEpochMilli(), TimeUnit.MILLISECONDS);
        System.out.println(epochSecondThreeMinsAgo);

        // One Day ago
        Instant oneDayAgo = instant.minus(1, ChronoUnit.DAYS);
        System.out.println(oneDayAgo);
        long epochSecondOneDayAgo = TimeUnit.SECONDS.convert(oneDayAgo.toEpochMilli(), TimeUnit.MILLISECONDS);
        System.out.println(epochSecondOneDayAgo);
    }
}

Output:

2022-09-15T06:21:19Z
2022-09-15T06:18:19Z
1663222699
2022-09-14T06:21:19Z
1663136479

Learn about the modern Date-Time API from Trail: Date Time.

  • Related