android项目中的日期格式[重复]

问题描述 投票:-1回答:3

这个问题在这里已有答案:

我正在制作一个新闻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;
}


}

我也在添加格式在JSON中的外观图像。

java android date datetime java-time
3个回答
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
投票
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);

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.