Reputation: 3
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
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
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
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