summerNight summerNight - 2 months ago 9
Scala Question

Get UTC time and format it without milliseconds

I have the following function that returns a

DateTime
format which I can easily print using the
toString
method.

def getUTCNow(): DateTime = {
val now = new Date()
val utc = new DateTime(now).withZone(DateTimeZone.UTC)
utc
}


However, it prints something like
2016-09-24T00:07:40.446Z
which is what I want but without the
.446
milliseconds character. How do I get that?

My end result should look like this:
2016-09-24T00:07:40Z

Answer

Using java and joda , this can be done as follows

DateTime dateTime =  new DateTime(new Date()).withZone(DateTimeZone.UTC);
System.out.println(dateTime.toString("yyyy-MM-dd'T'HH:mm:ss'Z'"));

In your case as well the equivalent should be similar to :

utc.toString("yyyy-MM-dd'T'HH:mm:ss'Z'")

prints : 2016-09-24T02:22:15Z