Backend Development 3 min read

Simple Java Utilities for Converting UTC to Beijing Time and Accessing Date Components

This article presents a straightforward Java solution that converts UTC timestamps to Beijing time by applying an 8‑hour offset and provides utility methods to retrieve the current week number, month, day, and year using the Calendar class.

FunTester
FunTester
FunTester
Simple Java Utilities for Converting UTC to Beijing Time and Accessing Date Components

Because the project requires using UTC timestamps during testing, the author looked for a simple way to convert UTC to the local Beijing time zone without complex calculations. The solution involves obtaining a Calendar instance set to UTC, adjusting its time by subtracting eight hours (the offset between UTC and Beijing), and then using this calendar to extract various date components.

The following method returns a Calendar object whose time is adjusted to Beijing time:

/**
 * Get a Calendar instance set to Beijing time (UTC‑8).
 *
 * @return Calendar object with adjusted time.
 */
public static Calendar getCalendar() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date(getDate().getTime() - 8 * 3600 * 1000));
    return calendar;
}

Additional helper methods built on top of getCalendar() provide convenient access to specific date fields:

/**
 * Get the current week number of the year.
 */
public static int getWeeksNum() {
    return getCalendar().get(Calendar.WEEK_OF_YEAR);
}

/**
 * Get the current month (1‑based).
 */
public static int getMonthNum() {
    return getCalendar().get(Calendar.MONTH) + 1;
}

/**
 * Get the current day of the month.
 */
public static int getDayNum() {
    return getCalendar().get(Calendar.DAY_OF_MONTH);
}

/**
 * Get the current year.
 */
public static int getYearNum() {
    return getCalendar().get(Calendar.YEAR);
}

These utilities are intended for regions that use Beijing time as the standard time zone. The article also includes links to previous related posts for further reading.

backendjavatimezoneUTCcalendardate-time
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.