Android项目中的日期格式

时间:2018-09-03 10:46:26

标签: java android date datetime java-time

我正在制作一个NEWS Android应用程序。 我使用JSON解析从NewaApi获取的所有数据。 我还将以“ YYYY-MM-DD”格式从API收集日期信息。 我想将格式转换为DD-MM-YYYY。 这是我的Adapter类的代码。

public class NewsAdapter extends ArrayAdapter<NewsData> {

public NewsAdapter(Context context, List<NewsData> news) {
    super(context, 0, news);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.news_list, parent, false);
    }


    NewsData currentNews = getItem(position);

    TextView headlineView = listItemView.findViewById(R.id.headline);
    headlineView.setText(currentNews.getmHeadline());

    String originalTime = currentNews.getmDate_time();
    String date;


    if (originalTime.contains("T")) {
        String[] parts = originalTime.split("T");
        date = parts[0];
    } else {
        date = getContext().getString(R.string.not_avilalble);
    }


    TextView dateView = listItemView.findViewById(R.id.date);
    dateView.setText(date);

    String imageUri=currentNews.getmImageUrl();
    ImageView newsImage = listItemView.findViewById(R.id.news_image);

    Picasso.with(getContext()).load(imageUri).into(newsImage);


    return listItemView;
}


}

A还添加了该格式在JSON中的外观图片。

3 个答案:

答案 0 :(得分:2)

如果它的格式为yyyy-MM-dd,则可以将其解析为LocalDate

如果它的格式为yyyy-MM-dd'T'HH:mm:ss'Z',则可以将其解析为OffsetDateTime,然后截断为LocalDate

示例代码:

public static String convert(String originalTime) {
    LocalDate localDate;

    if (originalTime.contains("T")) {
        localDate = OffsetDateTime.parse(originalTime).toLocalDate();
    } else {
        localDate = LocalDate.parse(originalTime);
    }

    return localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
}

测试用例:

public static void main(String args[]) throws Exception {
    System.out.println(convert("2000-11-10"));  // 10-11-2000
    System.out.println(convert("2000-11-10T00:00:01Z")); // 10-11-2000
}

答案 1 :(得分:1)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = sdf.parse(originalTime);
String newDate = new SimpleDateFormat("dd-MM-yyyy").format(date);

答案 2 :(得分:0)

将此方法放在utils类中,然后在需要的地方将此方法调用为Utils.getDate(“您的日期在这里”)。

public static String getDate(String ourDate) {
    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

    Date d = null;
    try {
        d = input.parse("2018-02-02T06:54:57.744Z");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formatted = output.format(d);
    Log.i("DATE", "" + formatted);

    return formatted;
}