-3

Using JDK 1.8 I have Time in ms for a day (not since 1970) and I have a Date how do I add the two and create a datetime.

Thanks Tried @Kikos soln does not produce correct result: Somehow my orig time 930 hrs in this case changes to 9:40, the orig date itself should not have any time gets time (??) - so the addition math fails.

   String testdate = "2015/10/25";
    Date date = new SimpleDateFormat("yyyy/mm/dd").parse(testdate);

    String timehrs= "930";
    long ltime = Long.parseLong("930");
    long hoursAsSeconds = (ltime / 100) * 60 * 60;
    long minsAsSeconds = (ltime % 100) * 60;
    long secondsOfDay = hoursAsSeconds + minsAsSeconds;

    System.out.println("testdate : "+ testdate +", timehrs: "+timehrs+" ,secondsOfDay: "+secondsOfDay); 
    System.out.println("Orig Date time formatted: "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date));

    Date dt = new Date(date.getTime() + secondsOfDay*1000);

    System.out.println("New Date : "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(dt);  

testdate : 2015/10/25, timehrs: 930, secondsOfDay: 34200 Orig Date time formatted: 2015-10-25 12:10:00 New Date : 2015-40-25 09:40:00
Expected : 2015-10-25 09:30:00

  1. Based on below by @Basil Bourque

    long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( secondsOfDay*1000 );
    LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay ); ZoneId z = ZoneId.systemDefault(); ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );

    System.out.println("ZonedDateTime zdt: "+ zdt);

    ZonedDateTime zdt: 2015-10-25T09:30-07:00[America/Los_Angeles]

This is the correct answer: 2015-10-25T09:30

Sam-T
  • 1,877
  • 6
  • 23
  • 51
  • 1
    Code example please. Example input and expected outputs please. – Boris the Spider Nov 29 '16 at 19:49
  • Possible duplicate of [Converting between java.time.LocalDateTime and java.util.Date](http://stackoverflow.com/questions/19431234/converting-between-java-time-localdatetime-and-java-util-date) – Flown Nov 29 '16 at 20:39
  • It's unclear what you have. When you say "Date", do you mean `java.util.Date`? Or just "a date", if then what is it? And what does *Time in ms for a day* mean? – Tunaki Nov 29 '16 at 20:44
  • `Date` is pretty obsolete and should be avoided if possible. Use the Java 8 classes such as LocalDate, LocalTime, LocalDateTime, Instant, DateTimeFormatter, .... – greg-449 Nov 29 '16 at 21:45
  • My Date is simply a java.util.Date created form a String (as per the code). The String does not have a time component but when I convert and format and see it has time. Also my time is simply time in ms for the day (not since 1970). – Sam-T Nov 29 '16 at 22:03
  • My expected output is : if I add "2015/10/25" and "930" - I should get **2015-10-25 09:30:00**. I am not getting that - multiple errors - time is **9:40** + month is somehow 40(???) – Sam-T Nov 29 '16 at 22:23
  • I am seeing comments that we should preferably use LocalDateTime instead of Date. I am not seeing any method to convert a String into LocalDateTime unless we go via Date. – Sam-T Nov 29 '16 at 22:54
  • You don't need to have an intermediate `Date`, see http://stackoverflow.com/questions/4216745/java-string-to-date-conversion, more specifically the "Java 8 update" part of the top answer. You can use a `DateTimeFormatter` to parse your String into a `LocalDateTime` (or others). – Tunaki Nov 30 '16 at 00:28
  • You say you have time of day as a count of milliseconds since midnight (apparently). Yet `930` would mean the time-of-day `00:00:00.930`, not `09:30:00.000`. Please edit your Question to clarify. – Basil Bourque Nov 30 '16 at 00:34
  • My time data is 24 hr format 930, 1230, 1430, etc. 930 means 9:30 am 1630 means 4:30 PM. I am converting it into milliseconds in the day - since midnight (not since 1970) – Sam-T Nov 30 '16 at 02:07

2 Answers2

1

Question is convoluted

You say you have time of day as a count of milliseconds since midnight (apparently). Yet 930 would mean the time 00:00:00.930, not 09:30:00 as shown in your example data. I will follow your text rather than your example data.

java.time

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. Forget you ever heard of java.util.Date and .Calendar.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

ISO 8601

The java.time classes use the ISO 8601 standard by default when parsing/generating strings representing date-time values. To make your input string standard, replace those slash characters with hyphens.

String input = "2015/10/25".replace( "/" , "-" );
LocalDate ld = LocalDate.parse( input );

By the way, this whole scheme you have been assigned is awkward, error-prone, and needlessly complicated. To serialize a date-time value for communication between systems, use the ISO 8601 string formats.

LocalTime

You say you have a count of milliseconds to represent the time of day as a count from midnight.

The LocalTime class offers factory methods to instantiate based on a duration of whole seconds and of nanoseconds. To get nanoseconds, simply multiply your milliseconds by one thousand. Better yet, let the TimeUnit enum do the work and make your code more self-documenting.

long millisOfDay = Long.parseLong( "930" );
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( millisOfDay );  // Same effect as: ( millisOfDay * 1_000L )
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );

ZonedDateTime

Now combine these two Local… objects along with a time zone to determine a point on the timeline. Was this date and time meant to be a moment in Montréal Québec, Paris France, Kolkata India, or Aukland New Zealand?

ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );

See live code in IdeOne.com.

ld.toString(): 2015-10-25

lt.toString(): 00:00:00.930

zdt.toString(): 2015-10-25T00:00:00.930+13:00[Pacific/Auckland]

LocalDateTime

If your data came with no information about time zone, and you cannot safely assume the intended time zone by your business scenario, you are left with no better option than combining into a LocalDateTime object. But keep in mind that this value is ambiguous. This value is not a point on the timeline. This value represents potential points on the timeline which can only be determined with a time zone assigned for ZonedDateTime or a offset-from-UTC assigned for OffsetDateTime.

LocalDateTime ldt = LocalDateTime.of( ld , lt );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Yes this is the exact answer that works for me. ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ); – Sam-T Nov 30 '16 at 02:33
0

something like:

Date dt = new Date(System.currentTimeMillis() + ms);
or
Date otherDate(....);
Date dt = new Date(otherDate.getTime() + ms);
Kiko
  • 319
  • 1
  • 4
  • 16
  • I tried this somehow fails - does not give correct result - some date format issues. I will elab in the Question. – Sam-T Nov 29 '16 at 21:31