-1

I am trying to get the current date and time and create a collection that contains my current time/date and the next hour and so on.

I am quite a beginner in Java and facing two problems. The output is :

Sat Oct 23 00:07:27 CET 1937

Sat Oct 23 01:07:27 CET 1937

  1. How can I get the date/time without CET 1973?
  2. Why the weekday (sat) is not the actual one (Monday) (2 days earlier)?

Source Code is :

    SimpleDateFormat format1 = new SimpleDateFormat("EEE, d  MMM  HH:mm");
    System.out.println(format1.getCalendar().getTime());
    format1.getCalendar().add(Calendar.HOUR, 1);        
    System.out.println(format1.getCalendar().getTime());
Community
  • 1
  • 1
Was
  • 1
  • 4
  • Please show the code that produces this output. Also, please clarify the question - Oct 23 1937 *is* Saturday, not Monday. Do you expect 1973? And CET applies to time; not year – Felix Oct 22 '17 at 22:26
  • Sat Oct 23 01:07:27 CET 1937 ... I want my output without (CET1937) and want the weekday to be the actual day which is in my case right now its Monday? – Was Oct 22 '17 at 22:31
  • You obviously don't get today's date! You are getting October 23, **1937**! Do you have wrong date in your computer? – Felix Oct 22 '17 at 22:44
  • `format1.getCalendar()` [doesn't return the current date](https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#getCalendar()). Use it like this `format1.format(new Date())`. Also make a search (in Google or in Stack Overflow itself) - I suggest *"how to get current date in java"* and *"how to format date in java"* - there are already hundreds of questions about this topic. –  Oct 22 '17 at 23:38
  • 1
    Recommended article: https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/ –  Oct 22 '17 at 23:43

1 Answers1

0

Verify the correct date and time is set on the host computer. Your computer seems to be set wrong. Visit http://time.is/

Use modern java.time classes rather than the troublesome old Calendar class.

Get the current moment in UTC, with a resolution of up to nanoseconds.

Instant instant = Instant.now() ;

Specify your desired/expected time zone.

ZoneId z = ZoneId.of( "Europe/Paris" ) ) ;

Adjust into desired time zone.

ZonedDateTime zdt = instant.atZone( z ) ;

Verify day-of-week.

DayOfWeek dow = zdt.getDayOfWeek() ;

Collect this moment and the each of the following two hours.

List< ZonedDateTime > moments = new ArrayList<>( 3 ) ;
moments.add( zdt ) ;
moments.add( zdt.plusHours( 1 ) ) ;
moments.add( zdt.plusHours( 2 ) ) ;

Generate a String to represent any of these values by using the DateTimeFormatter class. Search Stack Overflow for more info, as that has been covered many times already.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154