dsi
dsi

Reputation: 3359

Format date string to remove time in JAVA

Example, String value is:

15/08/2013 15:30 GMT+10:00 

I want to format above string to 15/08/2013 (remove time part and only keep date) in Java.

How can I do this format?

Upvotes: 4

Views: 19449

Answers (6)

MadProgrammer
MadProgrammer

Reputation: 347314

2018

Since it's now 2018 and we have the date/time API in Java 8+ (and the ThreeTen Backport), you could do something like...

String text = "15/08/2013 15:30 GMT+10:00";
LocalDateTime ldt = LocalDateTime.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm z", Locale.ENGLISH));
System.out.println(ldt);

// In case you just want to do some "date" manipulation, without the time component
LocalDate ld = ldt.toLocalDate();
// Will produce "2013-08-15"
//String format = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE);
String format = ldt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(format);

Original Answer

One approach would be to parse the String date to a Date object and then simply format as per your requirements

String text = "15/08/2013 15:30 GMT+10:00";
SimpleDateFormat inFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm z");
Date date = inFormat.parse(text);
System.out.println(date);

SimpleDateFormat outFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatted = outFormat.format(date);
System.out.println(formatted);

This has the nice benefit of preserving the date/time information in the Date should you need it for other things ;)

See, SimpleDateFormat for more details

Upvotes: 5

vcetinick
vcetinick

Reputation: 2017

Check out the DateFormat class, http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

You should be able to parse in the date using a parser and then write out your desired format in another pattern

i.e. new SimpleDateFormat("dd/MM/yyyy hh:mm z") for inbound

new SimpleDateFormat("dd/MM/yyyy") for your updated format

Upvotes: 0

Ran Adler
Ran Adler

Reputation: 3711

DateFormat formatter = new SimpleDateFormat(format);
Date date = (Date) formatter.parse(dateStr);

Upvotes: 0

Jesper
Jesper

Reputation: 206896

If this is nothing more than you have a string containing 15/08/2013 15:30 GMT+10:00 and you just want the date part, which is the first 10 characters of the string, I'd just take the first 10 characters; no need to parse and format it as a date:

String input = "15/08/2013 15:30 GMT+10:00";
String result = input.substring(0, 10);

Upvotes: 1

Lefteris Laskaridis
Lefteris Laskaridis

Reputation: 2322

Try using the SimpleDateFormat class: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122018

Remove time part and only keep date

String dateString= "15/08/2013 15:30 GMT+10:00";
String result  = dateString.split(" ")[0];

That gives you 15/08/2013

There is no need to formatter, I guess.

Upvotes: 12

Related Questions