Reputation: 193
I found different topics on this subject but couldn't find a proper solution to my problem yet. How can I get the current UTC time, add for example 60 minutes to it, and the display it in this format: HH:mm:ss ? Is it possible? Thanks
I used this to get the UTC time, but I don't know how to add minutes to it and the change the format to display:
val df: DateFormat = DateFormat.getTimeInstance()
df.timeZone = TimeZone.getTimeZone("utc")
val utcTime: String = df.format(Date())
I also tried this function but it displays the current time from the device:
fun getDate(milliSeconds: Long, dateFormat: String?): String? {
val formatter = SimpleDateFormat(dateFormat)
val calendar = Calendar.getInstance()
calendar.timeInMillis = milliSeconds
return formatter.format(calendar.time)
}
Upvotes: 4
Views: 13119
Reputation: 18578
Use java.time
here, you can get the current time of a specific offset or even time zone and output it afterwards using the desired pattern:
import java.time.format.DateTimeFormatter
import java.time.ZoneOffset
import java.time.OffsetDateTime
fun main() {
val dateTime = getDateTimeFormatted(50, "HH:mm:ss")
println(dateTime)
}
fun getDateTimeFormatted(minutesToAdd: Long, pattern: String): String {
// get current time in UTC, no millis needed
val nowInUtc = OffsetDateTime.now(ZoneOffset.UTC)
// add some minutes to it
val someMinutesLater = nowInUtc.plusMinutes(minutesToAdd)
// return the result in the given pattern
return someMinutesLater.format(
DateTimeFormatter.ofPattern(pattern)
)
}
The output of an execution some seconds before posting this was:
09:43:00
If you are supporting older API versions than 26, you might find out Java 8 features are not directly available there.
You can use them anyway, just read the answers to this question, the most recent way is API Desugaring
Upvotes: 9
Reputation: 2432
var dateformat = SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
dateformat.timeZone = TimeZone.getTimeZone("UTC")
var date = Date()
date.hours = date.hours +2
date.minutes = date.minutes + 30
Log.e("date",dateformat.format(date))
Upvotes: -4