0

I'm having a string like this: Wed Feb 20 02:48:00 GMT+05:30 2019 and I need to convert it to Wed 20.

How can I do this?

I tried string.replace(), but that doesn't help I'm a newbie please help

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Mr. V
  • 35
  • 4
  • `ZonedDateTime.parse("Wed Feb 20 02:48:00 GMT+05:30 2019", DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT)).format(DateTimeFormatter.ofPattern("EEE d", Locale.ENGLISH))`. – Ole V.V. Feb 28 '19 at 07:12

2 Answers2

1

If you will be working with dates that are always represented in this String format,
then perhaps you can use the String split method, to break apart your date on the spaces.

String sourceDate = "Wed Feb 20 02:48:00 GMT+05:30 2019";
String[] dateParts = sourceDate.split(" ");

This will result in an Array containing the seperate blocks.

dateParts = { 'Wed', 'Feb', '20','02:48:00', 'GMT+05:30', '2019' }

Then you can take the blocks you need

String resultDate = dateParts[0] +" "+ dateParts[2];

Wed 20


If you intend to do other manipulations on the date, you might want to look into converting your date String to an actual Date using a DateTimeFormatter

This works like this:

String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Where LocalDate.parse() needs to be replaced depending on your date format.
Only the date -> LocalDate#parse(text, formatter)
Date and time -> LocalDateTime#parse(text, formatter)
Date, time and timezone -> ZonedDateTime#parse(text, formatter)

George Derpi
  • 668
  • 4
  • 10
  • Even for a simple manipulation like this I would prefer to use the built-in date and time types as in your second example. It’s more high-level, tells the reader more clearly what is going on and why. And as you said, is future-proof in case one day we need for example `February` or `febrero` (in Spanish) or `02` instead of `Feb`. – Ole V.V. Feb 28 '19 at 08:19
0

try this

class Test
{
        public static void main(String ... args)
        {
                String s="Wed Feb 20 02:48:00 GMT+05:30 2019";
                String arr[]=s.split(" ");
                if (arr.length >=3)
                {
                        String result=arr[0]+" "+arr[2];
                        System.out.println(result);
                }
        }
}
$ java Test
Wed 20
satyesht
  • 499
  • 7
  • 19