yasi
yasi

Reputation: 483

Strip off seconds from joda DateTime java

I have an org.joda.time.DateTime object, its timezone is "Asia/Shanghai" (i.e. +08:00), the date time value of it is "2021-06-22T22:30:25+08:00". I want to strip off seconds from it without changing its original timezone. The expected value is "2021-06-22T22:30:00+08:00". How can I do the strip?

Upvotes: 0

Views: 180

Answers (3)

yasi
yasi

Reputation: 483

Referring to Ole V.V. and rzwitserloot's answers, the following solved my problem

dateTime = new DateTime(dateTime).withMillisOfSecond(0).withSecondOfMinute(0);

(Type of dateTime is org.joda.time.DateTime)

Upvotes: 0

Anonymous
Anonymous

Reputation: 86368

    DateTimeZone zone = DateTimeZone.forID("Asia/Shanghai");
    DateTime dt = new DateTime(2021, 6, 22, 22, 30, 25, zone);

    dt = dt.withMillisOfSecond(0).withSecondOfMinute(0);
    
    System.out.println(dt);
    System.out.println("Is time zone changed? It is now " + dt.getZone());

Output:

2021-06-22T22:30:00.000+08:00
Is time zone changed? It is now Asia/Shanghai

Bonus quote: The Joda-Time home page says:

Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

Link: Joda-Time home

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 103707

jodatime? It's 2021. Just use java.time. Which is jodatime with a few slight updates, and baked into the core java libraries.

At any rate, whether we're talking about jodatime or java.time, the data sturctures are immutable so what you want is impossible. You can't strip anything off. What you can do, is make new DateTime objects.

myOriginalObject.withSecondsOfMinute(0) does the job. Returns a new DT instance that has 00 for seconds.

Upvotes: 1

Related Questions