0

need help in java code to get current date and time in below format :

newdate = "Mon, 13 Jul 2020 14:08:30 GMT"

After this I need to replace current date with earlier one:

vJsonfile1.replace(earlierdate," "+ newdate);

SevvyP
  • 375
  • 1
  • 7
Rohan
  • 3
  • 2
  • Your question is not clear. Consider adding some details. you can get date and timestamp using date class, break it down into string if you want another format. this is a duplicate question, please refer to https://stackoverflow.com/questions/5175728/how-to-get-the-current-date-time-in-java – minigeek Jul 15 '20 at 19:52

3 Answers3

1

You can use ZonedDateTime and the RFC_1123 format to get the output you need:

DateTimeFormatter dtf = DateTimeFormatter.RFC_1123_DATE_TIME;

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("GMT"));

System.out.println(dtf.format(zdt));

Wed, 15 Jul 2020 19:07:37 GMT

Note the 1123_DATE_TIME format doesnt play nice with North American Time zones so itll work as long as its GMT or European time zones otherwise below will suffice too:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z");

ZonedDateTime zdt = ZonedDateTime.now();

System.out.println(dtf.format(zdt));

Wed, 15 Jul 2020 14:13:22 CDT

Which will output the current time with the time zone its in.

locus2k
  • 2,802
  • 1
  • 14
  • 21
0

This code does exactly what you wanted it to do.

Output:

  Mi, 15 Jul 2020 08:55:21 MESZ

Code:

 SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");
 Date currentDate = new Date();

 System.out.println(formatter.format(currentDate));
verity
  • 375
  • 1
  • 11
  • I get the output as : current Date is Wed, 15 Jul 2020 03:06:27 -0400. Instead of -0400 I need to print GMT , "Wed, 15 Jul 2020 03:06:27 GMT" . Can we do this with same command by changing last digit or something like this ? – Rohan Jul 15 '20 at 19:08
  • I am glad to hear that – verity Jul 15 '20 at 19:51
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jul 16 '20 at 02:57
0

Here is an example that formats your datetime and then changes the date portion of it:

ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z")));
zonedDateTime = ZonedDateTime.of(LocalDate.of(2020, 12, 15), zonedDateTime.toLocalTime(), zonedDateTime.getZone());
System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z")));
jnorman
  • 606
  • 8
  • 14