简体   繁体   中英

How do you convert Timestamp to normal time?

I am having this issue where when I post my timestamp shows excessive amount of information as shown in the image时间戳

However I am wondering how do you convert this to just time and date without GMT or year for example Sat Apr 03 14:00:00.

My add.java


    private void uploadData(String imageURL) {


        CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
                .document(user.getUid()).collection("Post Images");
        String id = reference.document().getId();
        String description = descET.getText().toString();

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("description", description);
        map.put("imageUrl", imageURL);
        map.put("timestamp", FieldValue.serverTimestamp());


        map.put("name", user.getDisplayName());
        map.put("profileImage",String.valueOf(user.getPhotoUrl()));
        map.put("likeCount", 0);
        map.put("Comments", "");
        map.put("uid", user.getUid());

        reference.document(id).set(map)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if(task.isSuccessful()){
                            System.out.println();
                            Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getContext(), "Error: "+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                    }
                });


    }

my profile.java

    private void uploadImage(Uri uri) {
        StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile Images");

        reference.putFile(uri)
                .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            reference.getDownloadUrl()
                                    .addOnSuccessListener(new OnSuccessListener<Uri>() {
                                        @Override
                                        public void onSuccess(Uri uri) {
                                            String imageURL = uri.toString();
                                            UserProfileChangeRequest.Builder request = new UserProfileChangeRequest.Builder();
                                            request.setPhotoUri(uri);

                                            user.updateProfile(request.build());
                                            Map<String, Object> map = new HashMap<>();
                                            map.put("profileImage", imageURL);
                                            map.put("date", FieldValue.serverTimestamp());
                                            FirebaseFirestore.getInstance().collection("Users")
                                                    .document(user.getUid())
                                                    .update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful())
                                                        Toast.makeText(getContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
                                                    else
                                                        Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                        }
                                    });
                        } else {
                            Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

Any help here would be greatly appreicated.

java.time

Consider using java.time, the modern Java date and time API. For a conversion from one string format to another, use two formatters:

private static final DateTimeFormatter inputParser
        = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz uuuu", Locale.ENGLISH);
private static final DateTimeFormatter outputFormatter
        = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm", Locale.ENGLISH);

With them do:

String givenStringDate = "Sat Apr 03 14:19:53 GMT+01:00 2021";
ZonedDateTime zdt = ZonedDateTime.parse(givenStringDate, inputParser);
String outputString = zdt.truncatedTo(ChronoUnit.HOURS).format(outputFormatter);
System.out.println(outputString);

Output is:

Sat Apr 03 14:00

Now we're at it, consider using Java's built-in localized format for the audience in question, for example:

private static final DateTimeFormatter outputFormatter
        = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                .withLocale(Locale.FRENCH);

03/04/21 14:00

You can make the format longer by specifying MEDIUM , LONG or FULL .

Question: Doesn't java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It's called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

You can do Like this:

public class Main {
     public static void main(String[] args) {
          String normalTime = convertTimestampToNormalTime("Sat Apr 03 14:19:53 
          GMT+01:00 2021");
          System.out.println(normalTime);
     }

     public static String convertTimestampToNormalTime(String timestamp) {
          String[] arrOfTime = timestamp.split("GMT");
          return arrOfTime[0];
     }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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