简体   繁体   English

在Android中以本地化格式与字符串分开显示日期和时间

[英]Displaying Date and Time separately from a String in localized format in Android

I know there are a lot of similar questions, and so far some of the solutions that I tried, but did not fully answer my question are: this , this , this , this , this , this , this , this , this , this , and a lot more. 我知道有很多类似的问题,到目前为止,一些我尝试过,但并没有完全回答我的问题的解决方案是: 这个这个这个这个这个这个这个这个这个这个 ,还有更多。

I am making an app where I get user's post from server and sort it by date, and also displaying date and time it was created in the post. 我正在制作一个应用程序,可以从服务器获取用户的帖子,并按日期对其进行排序,还显示在帖子中创建日期和时间的时间。 Right now I have a working solution , and I am doing it by converting string from a server in this format yyyy-MM-dd HH:mm:ss to my custom date and time format. 现在, 我有一个有效的解决方案 ,并且通过将服务器中的yyyy-MM-dd HH:mm:ss格式的字符串转换为我的自定义日期和时间格式来实现。

The problem is: I do not want to hard code a format, but instead I want to display it in the format that user phone has, and do it separately for both date and time . 问题是: 我不想对一种格式进行硬编码,而是想以用户电话所具有的格式显示它,并分别对日期和时间进行处理 By the local format of the phone I mean - am-pm/24 hour format, and same for the date format - dd-MM-YY, or MM-dd-YYYY, or dd-MM, etc. 我用手机的本地格式表示-am-pm / 24小时制,日期格式则相同-dd-MM-YY或MM-dd-YYYY或dd-MM等。

So far I have looked through a lot of solutions, most of which have that hardcoded format . 到目前为止,我已经研究了很多解决方案, 其中大多数都采用了硬编码格式 I try to avoid, but I think that additional problem is that I want to separate date and time from datetime string. 我尝试避免,但是我认为另一个问题是我想将日期和时间与datetime字符串分开。 The other problem is that the transformation is not separate for date and time . 另一个问题是, 转换在日期和时间上不是分开的

In short I want to format 2017-07-04 12:00:00 to 04 Jul 2017 and 12:00 PM , or 07/04/17 and 12:00 . 简而言之,我要格式化2017-07-04 12:00:0004 Jul 201712:00 PM07/04/1712:00 ie. 即。 Separating date and time into two strings, and displaying them in localized phone format . 将日期和时间分成两个字符串,并以本地电话格式显示

My Adapter: 我的适配器:

 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();
     }
 }

Usman Rana's answer is correct and well explained. 乌斯曼·拉纳(Usman Rana)的答案是正确的,并且得到了很好的解释。 What I want to contribite is the modern answer since the replacements for SimpleDateFormat and Date have been out for years now. 我想作出的贡献是现代的答案,因为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);

On my computer this prints 在我的计算机上打印

04-07-2017
12:00:00

And the idea is exactly what you asked for, these are the date format and the time format set up on my computer, so each device will print the date and the time in its own preferred way. 这正是您所要的,这就是在计算机上设置的日期格式和时间格式,因此每个设备都将以自己喜欢的方式打印日期和时间。

Beware that there's a potential time zone issue here. 请注意,这里可能存在时区问题。 If you want to display the server's time on the user's phone no matter where in the world the user is taking her/his phone, you should be fine. 如果您想在用户的手机上显示服务器的时间,无论用户在世界上哪个地方都使用她/他的手机,都应该没问题。 If you wanted to use the phone's time zone, you need to convert the date-time first, and for that you need to know the server time zone. 如果要使用电话的时区,则需要先转换日期时间,为此,您需要知道服务器的时区。 Or probably better, the server would need to send the date and time in UTC. 或者可能更好,服务器将需要以UTC发送日期和时间。

The modern Java date and time API that I am using will come natively to Android Java. 我正在使用的现代Java日期和时间API将原生于Android Java。 Until that happens, you will need the ThreeTenABP, the backport to Android Java 7. See How to use ThreeTenABP in Android Project . 在此之前,您将需要ThreeTenABP,这是向Android Java 7的反向移植。请参阅如何在Android Project中使用ThreeTenABP

First I strongly recommend that you save dates as long(1) and not as String It would simplify your code a lot. 首先,我强烈建议您将日期保存为long(1)而不是字符串,这样可以大大简化代码。 You can handle dates and display them in the current Locale without having a single formatting string like "yyyy_MM_dd" in your code. 您可以处理日期并将其显示在当前语言环境中,而无需在代码中使用单个格式字符串,例如“ yyyy_MM_dd”。

Then to get the Date or Time in current Locale just : 然后要获取当前语言环境中的日期或时间:

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

You can change to long or short format passing an argument to getDateInstance() or getTimenstance() 您可以更改为长格式或短格式,并将参数传递给getDateInstance()或getTimenstance()

(1) as long or Date because Date internally is a long. (1)为long或Date,因为内部的Date为long。

Let me explain in steps: 让我分步说明:

  1. You can get to know default date format of device. 您可以了解设备的默认日期格式。
  2. You must know the format of date that the server is sending to you. 您必须知道服务器发送给您的日期格式。
  3. Make a instance of calendar and set the dateTime as it is coming from server. 创建一个日历实例,并将dateTime设置为来自服务器。
  4. Then you can format date and time as following (input to SimpleDateFormat is the format that you determined in step 1): 然后,您可以按照以下方式格式化日期和时间(SimpleDateFormat的输入是您在步骤1中确定的格式):

Code: 码:

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()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM