0

As input, I get a string like HH:mm, which is UTC. But I need to convert the time to +3 hours (i.e. UTC +3).

For example, it was 12:30 - it became 15:30.

I tried this code, but its not working :(

fun String.formatDateTime(): String {
    val sourceFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    sourceFormat.timeZone = TimeZone.getTimeZone("UTC")
    val parsed = sourceFormat.parse(this)

    val tz = TimeZone.getTimeZone("UTC+3")
    val destFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    destFormat.timeZone = tz

    return parsed?.let { destFormat.format(it) }.toString()
}

How can i do this?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
onesector
  • 361
  • 5
  • 18
  • What have you tried so far? Does the date matter resp. does DST matter or could you simply add three hours? – deHaar Dec 14 '22 at 16:22
  • @deHaar I updated the question with the code that didn't work for me – onesector Dec 14 '22 at 16:27
  • hours += 3; if( hours >23){ hours-=24;} and format it – Style-7 Dec 14 '22 at 17:29
  • 1
    *but its not working* -- in which way not working? Which result are you observing instead, exactly? – Ole V.V. Dec 16 '22 at 08:23
  • 1
    Time zones tend to change their offset from UTC from time to time, not only because of summer time (DST). So given a time of day such as 12:30 and a time zone ID such as Asia/Kuwait, you will also need a date so that you can apply the correct offset for that date. – Ole V.V. Dec 16 '22 at 09:45
  • You will want to check what you get from `TimeZone.getTimeZone("UTC+3")`. Does this answer your question? [Java: getTimeZone without returning a default value](https://stackoverflow.com/questions/33373442/java-gettimezone-without-returning-a-default-value). Does [this](https://stackoverflow.com/questions/62325706/timezone-doesnt-match-up-right) and [this](https://stackoverflow.com/questions/67072438/error-when-i-try-to-change-my-time-date-to-utc-1)? – Ole V.V. Dec 16 '22 at 20:16

3 Answers3

5

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.

Solution using java.time API

Parse the given time string using LocalTime#parse and then convert it into a UTC OffsetTime by using LocalTime#atOffset. The final step is to convert this UTC OffsetTime into an OffsetTime at the offset of +03:00 which you can do by using OffsetTime#withOffsetSameInstant.

Note that you do not need a DateTimeFormatter to parse your time string as it is already in ISO 8601 format, which is the default format that is used by java.time types.

Demo:

class Main {
    public static void main(String args[]) {
        String sampleTime = "12:30";
        OffsetTime offsetTime = LocalTime.parse(sampleTime)
                .atOffset(ZoneOffset.UTC)
                .withOffsetSameInstant(ZoneOffset.of("+03:00"));
        System.out.println(offsetTime);

        // Gettting LocalTine from OffsetTime
        LocalTime result = offsetTime.toLocalTime();
        System.out.println(result);
    }
}

Output:

15:30+03:00
15:30

Online Demo

Alternatively,

class Main {
    public static void main(String args[]) {
        String sampleTime = "12:30";
        OffsetTime offsetTime = OffsetTime.of(LocalTime.parse(sampleTime), ZoneOffset.UTC)
                .withOffsetSameInstant(ZoneOffset.of("+03:00"));
        System.out.println(offsetTime);

        // Gettting LocalTine from OffsetTime
        LocalTime result = offsetTime.toLocalTime();
        System.out.println(result);
    }
}

Online Demo

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    Nice addition to simply adding 3 hours! This is better than my answer when it comes to considering daylight saving time and/or zones. – deHaar Dec 14 '22 at 18:17
  • 1
    @deHaar Thanks for your kind words. As long as an answer meets OP's requirement, it deserves credit and therefore your answer does deserve the credit. I hurriedly read your answer and thought to write this answer using the `OffsetTime`. I was so busy that I completed my answer in three attempts. I just returned to this page again. – Arvind Kumar Avinash Dec 14 '22 at 18:32
3

You can use java.time for this and if you just want to add a specific amount of hours, you can use LocalTime.parse(String), LocalTime.plusHours(Long) and DateTimeFormatter.ofPattern("HH:mm"). Here's a small example:

import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun String.formatDateTime(hoursToAdd: Long): String {
    val utcTime = LocalTime.parse(this)
    val targetOffsetTime = utcTime.plusHours(hoursToAdd)
    return targetOffsetTime.format(DateTimeFormatter.ofPattern("HH:mm"))
}

fun main() {
    println("12:30".formatDateTime(3))
}

Output is simply 15:30.

Try it with "22:30" and you'll get "01:30" as output.

Please note that daylight saving time may cause problems if you are not supposed to just add three hours but consider a real time zone whose offset from UTC may change.

deHaar
  • 17,687
  • 10
  • 38
  • 51
2
@SuppressLint("SimpleDateFormat")
fun getDayOfWeekOfMonthDateFormat(timeZone: String? = "GMT"): SimpleDateFormat {
    val format = SimpleDateFormat("MMMM EEEE dd")
    timeZone?.let {
        format.timeZone = TimeZone.getTimeZone(it)
    }
    return format
}

This is function for returning "GMT" as default and if you wanna change, add "GMT+5:30"

NB: change the format with your requirement

MFazio23
  • 1,261
  • 12
  • 21