1

this is my "19-Aug-2019 11:05" string and I need to convert into dd-mmm-yyy hh:mm format(in GMT), separately I need to get the current GMT time also, appreciate your help,

Date date1 = sdf.parse(lastupdated2)

println date1
//println lastupdated2

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));```
jmq
  • 1,559
  • 9
  • 21
lahimadhe
  • 374
  • 2
  • 16
  • 1
    You can check this link - https://stackoverflow.com/questions/7670355/convert-date-time-for-given-timezone-java Hope it helps :) – Ashwani Arya Aug 19 '19 at 11:40
  • 1
    Is there a soecifc reason you are using the old legacy date api and not the modern date-time api that came with java 8? – Zabuzard Aug 19 '19 at 15:33

2 Answers2

1

Use SimpleDateFormat's parse() method to parse it to a Date Object.

String sDate1="19-Aug-2019 11:05";  
Date date1=new SimpleDateFormat("dd-MMM-yyyy HH:mm").parse(sDate1); 

For your other question - to get current GMT time you can use this:

final Date currentTime = new Date();

final SimpleDateFormat sdf =
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));
  • Is there a soecifc reason you are using the old legacy date api and not the modern date-time api that came with java 8? – Zabuzard Aug 19 '19 at 15:33
  • https://stackoverflow.com/users/7842456/chamidu-supeshala for your answer 1 this was the output : Tue Aug 20 07:52:00 IST 2019 my code ```Date date1=new SimpleDateFormat("dd-MMM-yyyy HH:mm").parse(tokens[1]); println date1 ``` – lahimadhe Aug 20 '19 at 08:01
  • what is the string value in tokens[1] variable? the part 1 of my answer creates a Java Date object with the string you given as argument to the parse() method. What you actually want to accomplish? the question is not quite a clear. – chamidu supeshala Aug 20 '19 at 08:18
  • @Zabuza, yes you are correct. But he didn't specified the version of java that he uses. As he already tried using legacy api, i tried to correct his approach using the same api. – chamidu supeshala Aug 20 '19 at 08:19
  • Fair enough. But maybe you can offer both solutions to increase the quality of your answer :) – Zabuzard Aug 20 '19 at 22:41
1

If you want to find the date from your input string you can use regex:

String lastupdated = "Mubasher Last Update Time: 20-Aug-2019 07:42 (GMT)";
Pattern p = Pattern.compile("\\d{2}-\\w{3}-\\d{4} \\d{2}:\\d{2}");
Matcher m = p.matcher(lastupdated);
m.find();
System.out.println(m.group());

If you also want to convert it to a date for further processing, I recommend to use LocalDateTime.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm",Locale.US);
LocalDateTime updateTime = LocalDateTime.parse(m.group(),dtf);
System.out.println(updateTime.format(dtf));
Eritrean
  • 15,851
  • 3
  • 22
  • 28