How to convert this string to standard date in java?

I posted the following question earlier: How can I convert this date to Java?

But now I would like to know how I can convert this string to a date / time.

2010-03-15T16:34:46Z

For example: 03/15/10

UPDATED:

String pattern = "MM/dd/yy 'at' HH:mm";
                Date date = new Date();
                try {
                    date = new SimpleDateFormat(pattern).parse(q.getUpdated_at());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));

Gives me the result:

Mon Mar 15 16:34:50 MST 2010

How can I format it as

03/15/10 at 4:34PM

?

+3
source share
3 answers

In a nutshell, you want to convert a date in string format to a date in another format. You have:

2010-03-15T16:34:46Z

and you want

03/15/10 at 4:34PM

java.util.Date , . toString(), , javadoc.

- . java.text.SimpleDateFormat. -, Date, .

// First parse string in pattern "yyyy-MM-dd'T'HH:mm:ss'Z'" to date object.
String dateString1 = "2010-03-15T16:34:46Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString1);

// Then format date object to string in pattern "MM/dd/yy 'at' h:mma".
String dateString2 = new SimpleDateFormat("MM/dd/yy 'at' h:mma").format(date);
System.out.println(dateString2); // 03/15/10 at 4:34PM
+2

SimpleDateFormat joda-time DateTimeFormat , :

String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";

:

Date date = new SimpleDateFormat(pattern).parse(dateString);

(joda-time):

DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(s);

- . :

dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));

(, SimpleDateFormat )

+8

If you want to format the output line, change the following line in the code

dateText.setText(date.toString());

to

dateText.setText(String.format("%1$tm/%1$td/%1$ty at %1$tl:%1$tM%1$Tp", date));
0
source

Source: https://habr.com/ru/post/1766574/


All Articles