【问题标题】:Displaying Date and Time separately from a String in localized format in Android在Android中以本地化格式与字符串分开显示日期和时间
【发布时间】:2017-12-07 18:49:34
【问题描述】:

我知道有很多类似的问题,到目前为止,我尝试过但没有完全回答我的问题的一些解决方案是:thisthisthisthis、@ 987654325@、thisthisthisthisthis 等等。

我正在制作一个应用程序,我从服务器获取用户的帖子并按日期对其进行排序,并显示它在帖子中创建的日期和时间。现在我有一个可行的解决方案,我正在将来自服务器的字符串以yyyy-MM-dd HH:mm:ss 格式转换为我的自定义日期和时间格式。

问题是:我不想对格式进行硬编码,而是想以用户手机的格式显示它,并且分别为日期和时间。我的意思是手机的本地格式 - am-pm/24 小时格式,日期格式相同 - dd-MM-YY、MM-dd-YYYY 或 dd-MM 等。

到目前为止,我已经浏览了很多解决方案,其中大部分都采用硬编码格式。我尽量避免,但我认为另一个问题是我想将日期和时间与日期时间字符串分开。另一个问题是日期和时间的转换不是分开的

简而言之,我想将2017-07-04 12:00:00 格式化为04 Jul 201712:00 PM,或者07/04/1712:00。 IE。 将日期和时间分成两个字符串,并以本地化电话格式显示

我的适配器:

 public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

     private List<UserPosts> postItems;
     private Context context;
     private static final String TAG = UserPosts.class.getSimpleName();

     class PostsViewHolder extends RecyclerView.ViewHolder {
    TextView userPostsTitle, userPostsDate, userPostsTime, userPost, textViewStars, textViewComments;
         ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
         String pCcontactId, postId;

         PostsViewHolder(View itemView) {
             super(itemView);

             userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
             userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
             userPostsTime = (TextView) itemView.findViewById(R.id.userPostsTime);
             userPost = (TextView) itemView.findViewById(R.id.userPost);

             textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
             textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

             imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
             imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
             imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
         }
     }

     public UserPostsAdapter(List<UserPosts> postsList, Context context) {
         this.postItems = postsList;
         this.context = context;
     }

     @Override
     public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

         return new UserPostsAdapter.PostsViewHolder(itemView);
     }

     @Override
     public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
         final UserPosts post = postItems.get(position);

         SQLiteHandler db = new SQLiteHandler(context.getApplicationContext());
         HashMap<String, String> user = db.getUserDetails();
         final String currentUserId = user.get("uid");

         if (post.getTitle() != null && !post.getTitle().isEmpty()) {
             holder.userPostsTitle.setText(post.getTitle());
         } else {
             holder.userPostsTitle.setVisibility(View.GONE);
         }
         holder.userPostsDate.setText(convertDate(postItems.get(position).getCreatedDate()));
         holder.userPostsTime.setText(convertTime(postItems.get(position).getCreatedTime()));
         holder.userPost.setText(post.getPostedText());
         if (Integer.parseInt(post.getLikesNumber()) > 0) {
             holder.textViewStars.setText(post.getLikesNumber());
         }
         holder.textViewComments.setText(post.getCommentsNumber());

         holder.pCcontactId = post.getUserId();
         final String postId = holder.postId = post.getId();

         holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
     });

     ***TRANSFORMING DATE AND TIME SEPARATELY TO CUSTOM FORMAT***
-----------------------------------------------------------------------------
private String convertDate(String time) {

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
    java.util.Locale.getDefault());

    SimpleDateFormat(datePattern);

      DateFormat.getTimeInstance(DateFormat.SHORT).parse(mTimeDisplay.getText().toString());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {

    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat("HH:mm", Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}
-----------------------------------------------------------------------------
     @Override
     public int getItemCount() {
         return postItems.size();
     }
 }

【问题讨论】:

  • @UsmanRana 谢谢你的回答乌斯曼。我确实尝试过,但它没有回答我的问题。我要做的是从服务器获取此字符串:yyyy-MM-dd HH:mm:ss,将其切割成两个字符串:yyyy-MM-ddHH:mm:ss,并将它们分别格式化为本地格式。
  • 让我逐步解释: 1)您可以了解设备的默认日期格式。 2) 您必须知道服务器发送给您的日期格式。 3)创建一个日历实例并将日期时间设置为来自服务器。 4) 然后您可以按以下方式格式化日期和时间(SimpleDateFormat 的输入是您在步骤 1 中确定的格式): String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime ()); String formattedTime = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
  • @UsmanRana 感谢您的解决方案,并在投票前阅读我的问题 :) 你能回答这个问题,所以我可以接受你的回答 :) 再次感谢您的帮助
  • 感谢您在询问之前搜索高低。我认为您没有找到重复项的原因之一是您确实在一个问题中至少提出了两个问题:(1)如何解析来自服务器的日期时间字符串(2)如何使用格式化日期和时间设备的格式设置。如果可以的话,最好发布两个单独的问题。

标签: java android date-format datetime-format time-format


【解决方案1】:

首先我强烈建议您将日期保存为 long(1) 而不是 String 这将大大简化您的代码。您可以处理日期并在当前区域设置中显示它们,而无需在代码中使用像“yyyy_MM_dd”这样的单一格式字符串。

然后获取当前语言环境中的日期或时间:

String dateLocalizedStr = DateFormat.getDateInstance().format(myDate);
String timeLocalizedStr = DateFormat.getTimeInstance().format(myDate);

您可以更改为长格式或短格式,将参数传递给 getDateInstance() 或 getTimenstance()

(1) as long 或 Date,因为 Date 内部是 long。

【讨论】:

  • 感谢您的回答,因为我从服务器接收所有数据,我认为将其保存为字符串会更容易。
【解决方案2】:

让我分步解释:

  1. 您可以了解设备的默认日期格式。
  2. 您必须知道服务器发送给您的日期格式。
  3. 创建日历实例并设置日期时间 来自服务器。
  4. 然后你可以格式化日期和时间如下(输入到 SimpleDateFormat 是您在步骤 1) 中确定的格式:

代码:

String formattedDate = new SimpleDateFormat("yyyy-MM dd", Locale.getDefault())
        .format(Calendar.getInstance()‌​.getTime()); 

String formattedTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        .format(Calendar.getInstance().g‌​etTime()); 

【讨论】:

  • @Tonteria24 提供的代码没有,但解释正确地解释了如何做到这一点。
【解决方案3】:

Usman Rana’s answer 是正确的并且解释得很好。我想贡献的是现代答案,因为 SimpleDateFormatDate 的替代品已经出现多年了。

    String dateTimeString = "2017-07-04 12:00:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
    String formattedDate 
            = dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
    System.out.println(formattedDate);
    String formattedTime 
            = dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
    System.out.println(formattedTime);

在我的电脑上打印

04-07-2017
12:00:00

这个想法正是你所要求的,这些是我电脑上设置的日期格式和时间格式,所以每个设备都会以自己喜欢的方式打印日期和时间。

请注意,这里可能存在时区问题。如果你想在用户的手机上显示服务器的时间,无论用户在世界的​​哪个地方拿她/他的手机,你应该没问题。如果你想使用手机的时区,你需要先转换日期时间,为此你需要知道服务器的时区。或者可能更好,服务器需要以 UTC 格式发送日期和时间。

我使用的现代 Java 日期和时间 API 将原生于 Android Java。在此之前,您将需要 ThreeTenABP,即 Android Java 7 的反向移植。请参阅How to use ThreeTenABP in Android Project

【讨论】:

  • 感谢您阅读我的问题和您的回复 :) 我之前确实在寻找与 Usman 和您的类似的答案,但找不到任何答案。希望这对其他人也有帮助。再次感谢:)
猜你喜欢
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多