Simple Fellow
Simple Fellow

Reputation: 4622

How to get time and date parts separately from an existing java.util.Date object

I have been trying and trying but I'm pretty surprised as not to be able to find a solution for my simple problem.

I have a date variable which has value like this:

res0: java.util.Date = Mon Jul 15 07:50:59 AET 2019

now I want only the Date part not the time. the functions available in the Date for such are deprecated. and all the solutions I found were using Calendar instance to get today's datetime and convert it into string using SimpleDateFormat.

I don't want a string. I want a Date without the time part and a time without the date part.

Upvotes: 3

Views: 8139

Answers (5)

MilanRegmi
MilanRegmi

Reputation: 519

We can do this using the date formatter, you can try the following code.

object DateFormatter extends App {
  val sdf = new SimpleDateFormat("EEEE MMMM dd, HH:mm:ss:SSS Z yyyy", Locale.ENGLISH)
  val date = new Date()
  val nowDate = sdf.format(date)
  println(nowDate)
  // It prints date in this format Monday July 22, 23:40:07:987 +0545 2019

  // Lets print the date in the format you have provided in your question
  val parsedDate = sdf.parse(nowDate)
  println(parsedDate)

  // Now, we have same date format as yours

  // Now we have to remove the time and keep the date part only, for this we can do this
  val newDateFormat = new SimpleDateFormat("yyyy-MM-dd")
  val dateOnly = newDateFormat.format(parsedDate)
  println(dateOnly)

  //Printing time only
  val timeFormatter = new SimpleDateFormat("HH:mm:ss")
  val timeOnly = timeFormatter.format(parsedDate)
  println(timeOnly)

  }

Output:

nowDate: Tuesday July 23, 07:08:05:857 +0545 2019
parsedDate: Tue Jul 23 07:08:05 NPT 2019
dateOnly: 2019-07-23
timeOnly: 07:08:05

Update

val dateNotInString = newDateFormat.parse(dateOnly)
  println(dateNotInString)

Output of Update:

dateNotInString: Tue Jul 23 00:00:00 NPT 2019

Here, you can see that dateNotInString is a date object and it does not contain any time related info. Similarly, time only info can be extracted.

Second Update

We can’t have a Date without the time part and without the date part using the SimpleDateFormat with type not String but we can convert it into LocaleDate and LocaleTime.

import java.time.Instant

  val instantTime = Instant.ofEpochMilli(parsedDate.getTime)

  import java.time.LocalDateTime
  import java.time.LocalTime
  import java.time.ZoneId

  val res = LocalDateTime.ofInstant(instantTime, ZoneId.systemDefault).toLocalTime
  println("localeTime " + res)

  val res1 = LocalDateTime.ofInstant(parsedDate.toInstant,ZoneId.systemDefault).toLocalDate
  println("localeDate " + res1)

Output of the second Update

localeTime: 18:11:30.850
localeDate: 2019-07-23

It's type is LocaleTime and LocaleDate respectively now.

Upvotes: 1

Basil Bourque
Basil Bourque

Reputation: 339561

tl;dr

myJavaUtilDate
.toInstant()
.atZone(
    ZoneId.of( "Australia/Sydney" )
) 
.toLocalDate() 

For time-of-day only, without date and without time zone:

.toLocalTime()

To generate a string, call:

.format(
    DateTimeFormatter
    .ofLocalizedDate( FormatSyle.MEDIUM )
    .withLocale( new Locale( "en" , "AU" ) )
)

Details

Immediately convert your java.util.Date from its legacy class to the modern replacement, Instant.

Instant instant = myJavaUtilDate.toInstant() ;

Both of those classes represent a moment as seen in UTC, that is, an offset of zero hours-minutes-seconds. Adjust into a time zone by which you want to perceive the date.

For any given moment the time-of-day and the date both vary by time zone around the globe. Noon in Paris is not noon in Montréal. And a new day dawns earlier in the east than in the west. You must get very clear on this to do proper date-time handling. One moment in nature can be viewed in many ways through human-created notions of time zones.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as AET, EST, or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Australia/Sydney" ) ;

Apply to the Instant to get a ZonedDateTime. Both represent the same simultaneous moment, but are viewed with a different wall-clock time.

ZonedDateTime zdt = instant.atZone( z ) ;

Extract the date-only portion.

LocalDate ld = zdt.toLocalDate() ;

Extract the time-of-day portion.

LocalTime lt = zdt.toLocalTime() ;

Put them back together again.

ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

If you need a java.util.Date again to interoperate with old code not yet updated to java.time, convert.

Date d = Date.from( zdt.toInstant() ) ;

Upvotes: 6

pme
pme

Reputation: 14803

You can use LocalDate

val input = new Date() // your date
val date = input.toInstant().atZone(ZoneId.of("Europe/Paris")).toLocalDate()

Here is a good answer: https://stackoverflow.com/a/21242111/2750966

Upvotes: 2

anthony yaghi
anthony yaghi

Reputation: 550

    Date date = new Date(res0.getTime() - (res0.getTime() % 86400000));
    System.out.println(date);

Now you can use the date formatter as is with your res0 date and it will print the date only. But what I tried to do is remove the time part basically 86400000 is the number of milliseconds per day and getTime return the number of milliseconds passed since January 1, 1970, 00:00:00 GMT. So basically this is equivalent to the date at time 00:00.00 of each day. I don't know if this is what you want because Date doesn't hold 2 separate things like date and time it just has a single long.

Upvotes: 0

Mysterious Wolf
Mysterious Wolf

Reputation: 373

You could use date formatter to turn it into String and parse it back to Date.

For example:

Date yourDate = ...;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateFormat.format(yourDate));

The new date object now only has the date part, with the time part being filled with zeroes. For a numeric solution with the same result, check out this answer. Alternatively, if you don't want the time part at all, this answer should suit you better.

Upvotes: 1

Related Questions