Rohan
Rohan

Reputation: 3

How can I get the current date and time in below format , date = "Mon, 13 Jul 2020 14:08:30 GMT"

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);

Upvotes: 0

Views: 364

Answers (3)

locus2k
locus2k

Reputation: 2935

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.

Upvotes: 1

verity
verity

Reputation: 385

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));

Upvotes: 0

jnorman
jnorman

Reputation: 626

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")));

Upvotes: 0

Related Questions