Hello I have a method which adds a time to my current time. What I am looking for is I want to add this code a local time info because doesnt get the local time in my country correctly. I searched in the stackoverflow but couldnt find a similar topic for this case. I am open your suggestions, thank you.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class MyClass {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 8);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
System.out.println(dateFormat.format(cal.getTime()));
}
}
I have changed the code with java.time utilities
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class MyClass {
public static void main(String args[]) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime date = LocalDateTime.now();
System.out.println(dateFormat.format(date));
System.out.println(dateFormat.format(date.plusHours(10)));
}
}
CodePudding user response:
Unfortunately you cannot really use the timezone because you get it from your operating system. If the OS gives you UTC, either configure it to Turkey or change it inside the application.
Since you know your location, just do this:
LocalDateTime date = LocalDateTime.now((ZoneId.of("Europe/Istanbul"));
This question from below might help : how can i get Calendar.getInstance() based on Turkey timezone
You can also deduce your timezone using your internet provider. Below there are 2 examples.
timezone example 1
RestTemplate restTemplate = new RestTemplate();
String timezone = restTemplate.getForObject("https://ipapi.co/timezone", String.class);
timezone example 2
String timezone = restTemplate.getForObject("http://ip-api.com/line?fields=timezone", String.class);
After getting the timezone:
LocalDateTime date = LocalDateTime.now(ZoneId.of(timezone));