How can I get the Date Time of current logged in user and parse it

To get the Date and Time or the currently logged in user, I have found a solution that works well:

// import com.atlassian.jira.datetime.DateTimeFormatter;
// import com.atlassian.jira.datetime.DateTimeStyle;

DateTimeFormatter formatter = dateTimeFormatter.forLoggedInUser();

// This code will produce String "27/Jan/21 4:42 PM"
String userTime = formatter
     .withStyle(DateTimeStyle.COMPLETE)
     .format(new Date()); // 27/Jan/21 4:42 PM

To parse the time to my custom format, I use this:

// import java.time.format.DateTimeFormatter;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

// This code will parse the Time to my custom format.
// But the LocalDateTime.now() will get the Time of JVM, not of the Jira User
return formatter.format(LocalDateTime.now())

I can’t find any way to combine them together, which means format the current user’s date to my custom format.

Thanks a lot for your help!

In case someone has the same issue in the future, this is the solution:

// Inject this
// import com.atlassian.jira.timezone.TimeZoneManager;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

// Get TimeZone of the current logged in user
TimeZone timeZone = timeZoneManager.getLoggedInUserTimeZone();

// Get the user's time
LocalDateTime usersTime = LocalDateTime.now(timeZone.toZoneId())

return formatter.format(usersTime);
1 Like