I'm pretty new to java and am trying to format a time using 24 hour format. I've come across two ways of formatting the hour - HH and kk:
SimpleDateFormat format1 new SimpleDateFormat("HH:mm");
SimpleDateFormat format2 new SimpleDateFormat("kk:mm");
Date date = new Date();
System.out.println(format1.format(date));
System.out.println(format2.format(date));
These both produce something like 11:21. What's the difference between them? Am I missing something?
The two formats essentially do the same thing but differ in how they handle midnight. kk will format midnight to 24:00 whereas HH will format to 00:00. The hours in a day in k are 1-24 and in H are 0-23
It's always worth checking the java documentation as it generally provides very useful explanations as well as examples of uses.
try this to see the difference
SimpleDateFormat format1 = new SimpleDateFormat("HH:mm");
SimpleDateFormat format2 = new SimpleDateFormat("kk:mm");
Date date = new GregorianCalendar(2001, 0, 1, 0, 0 , 0 ).getTime();
System.out.println(format1.format(date));
System.out.println(format2.format(date));
output
00:00
24:00
Related
I am currently trying to get create a java Date which looks the same no matter what timezone I view it in. My current code is:
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JANUARY, 8, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
In my current timeZone this gives me '2015-01-08T00:00:00Z'In another this gives me 2015-01-08T00:00:00-03:00. What I want to know is if there is any way to drop the timezone part so as the time is the same in both time zones.
I would be VERY grateful for any help on this matter. Thank you.
Java SE 8 comes with a new Date & Time API. Have a look at LocalDate and LocalDateTime.
If you are only interested in the format of the time, create a java.text.SimpleDateFormat object to print your time in the format that you want.
http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
If you want the time to be printed with the same numbers no matter the TimeZone,
Use String ids[] = java.util.TimeZone.getAvailableIDs();
to get the TimeZone's IDs and find the ID that you want.
In this example, I created two SimpleDateFormat objects set to two different TimeZones. They both print off the same Calendar object. I have taken off the Z in ft2 to remove the time zone portion. By relying on toString(), I think you would be subject to Locale differences in displaying dates, like US MM/dd/yyyy and UK dd/MM/yyyy.
TimeZone tz = TimeZone.getTimeZone("America/New_York");
TimeZone tz2 = TimeZone.getTimeZone("America/Chicago");
Calendar acal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss Z");
ft.setTimeZone(tz);
SimpleDateFormat ft2 = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss");
ft2.setTimeZone(tz2);
String date1 = ft.format(acal.getTime());
System.out.println(date1);
String date2 = ft2.format(acal.getTime());
System.out.println(date2);
Output:
2015-01-08T10:36:39 -0500
2015-01-08T09:36:39
I want to subtract two dates (one constant and one current) in Java but I've got strange problems with it. Here is the code :
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
Date currentTime = new Date();
long diff = FirstLessonInterval.getTime()-currentTime.getTime();
String s = String.valueOf(diff);
LessonOrBreak=(diff);
I've got minus minutes. When I want to see FirstLessonInterval with FirstLessonInterval.toString() it shows the year 1970. What can I do?
You forgot to give a date, you just defined a time:
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
and this is in unix time day 0 which is the 1.1.1970
try something like
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:MM");
Date FirstLessonInterval=df.parse("2014/05/10 08:45");
1970 is where all time began according to computers. Are we missing some code in your question? You can faff around with the current time in milliseconds but i'd take a look at JodaTime and use that.
The reason you are getting 1970.... is because I suspect your diff is quite a small number. Then if you look at that as a date then it will be a small number + 1 Jan 1970 which will still be in 1970. But as i said I suspect we are missing some code in your question.
In JodaTime you can do somethign like the below but im not sure what it is you are exactly after
Interval i= new Interval(new DateTime(FirstLessonInterval), new DateTime());
System.out.println("Interval is: " + i.toDurationMillis());
Your format pattern is incorrect, use lower case mm to represent minutes
When you do not specify much details to the outdated Java date api, it considers the time since UNIX epoch (1st Jan 1970)
Since you are assuming the date to be the same as the constant time parameters you provide and independent of the timezones, you can bring your current date comparable to the time since UNIX epoch:
Staying close to your original code;
DateFormat df = new SimpleDateFormat("HH:mm");
Date firstLessonInterval = df.parse("08:45");
Date currentTime = new Date();
// Format the current date comparable to UNIX epoch (only hold time params)
String dateStr = df.format(currentTime.getTime());
// Parse the modified date string to a date object
Date comDate = df.parse(dateStr);
// Take the difference in millis
long diff = firstLessonInterval.getTime() - comDate.getTime();
String s = String.valueOf(diff);
// Print the number of minutes passed since
System.out.println("Minutes {elapsed since/time to} 08:45 - " + Math.abs(diff) / 1000 / 60);
Missing Date Portion
As the other correct answers said, you are using the java.util.Date class which is a date-time class holding both a date portion and a time portion.
LocalTime
If you truly care about only time of day, with no date and no time zone, then use the LocalTime class found in both the Joda-Time library and the new java.tome package in Java 8. By the way the old java.util.Date and .Calendar classes are notoriously troublesome and should be avoided.
Joda-Time
Here is some code with date-time and time zone.
Using the Joda-Time 2.3 library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Warsaw" );
DateTime dateTime = new DateTime( 2014, 1, 2, 8, 45, 0, timeZone );
DateTime now = new DateTime( 2014, 1, 2, 8, 30, 0, timeZone ); // Or DateTime.now( timeZone )
Duration duration = new Duration( dateTime, now ); // or use Period or Interval.
Joda-Time offers intelligent classes and methods of working with a span of time (a Period, Interval, or Duration). For example look at the Minutes class. But if all you need is millseconds, here you go.
long millis = duration.getMillis();
The problem is that you are not providing enough info to SimpleDateFormat. It sets the hour and minutes correctly but nothing else.
DateFormat df = new SimpleDateFormat("HH:mm");
System.out.println(df.parse("08:45")); // Thu Jan 01 08:45:00 GMT 1970
System.out.println(new Date()); // Sun May 11 07:52:50 GMT 2014
If you want your date to be with respect to the current date try this:
Date curr = new Date();
Date date = new Date(curr.getYear(),
curr.getMonth(),
curr.getDate(),
8, 45, 0);
System.out.println(date); // Sun May 11 08:45:00 GMT 2014
System.out.println(curr); // Sun May 11 07:52:50 GMT 2014
long diff = date.getTime() - curr.getTime();
System.out.println("Minutes: " + diff/6000); // Minutes: 53
I dont know if this way is efficient or not but it's an idea anyway:
Date curr = new Date();
Date date = new Date(114, /*114 is 2014 , don't know why*/
6,
16,
8, 45, 0);
System.out.println(curr);
System.out.println(date);
Date x = new Date(curr.getYear() - date.getYear() ,
curr.getMonth() - date.getMonth(),
curr.getDate() - date.getDate(),
curr.getHours() - date.getHours(),
curr.getMinutes() - date.getMinutes(),
curr.getSeconds() - date.getSeconds() );
String startDateString = "2017-03-08";
String finishDateString = "2017-03-10";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
LocalDate startDate = LocalDate.parse(startDateString, formatter);
LocalDate finishDate = LocalDate.parse(finishDateString, formatter);
Integer day = finishDate.compareTo(startDate);
Integer day will be 3. It means that the difference between two dates equals 3 days
I have used following line code to display time in 24-Hour format from the Calendar Instance
Everything show correctly, but only problem is while showing time at midnight 12:00 am, It show time as 24:00 instead of showing 00:00. Why this happen anything wrong in my code.
Calendar m_CalInstance = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("kk:mm");
String timeDisplay = formatter.format(m_CalInstance.getTime());
SimpleDateFormat formatter = new SimpleDateFormat("kk:mm");
should be
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Check this javadoc for more information on SimpleDateFormat
use capital letters KK inplace of kk here
SimpleDateFormat formatter = new SimpleDateFormat("KK:mm");
I have below code snippet
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
String processedContentDate="2012-04-10 12:53:28.033";
java.util.Date parsedDate = dateFormat.parse(processedContentDate);
java.sql.Timestamp timestamp = new java.sql.Timestamp(
parsedDate.getTime());
I get parsed date as Tue Apr 10 00:53:28 IST 2012 and timestamp as 2012-04-10 00:53:28.033 . i want to get the time exactly as 12:53:28.033(as in my original string)
not 00:53:28.033. Not getting why 12:53:28 is getting converted to 00:53:28. what should I do to get 12:53:28?
EDIT: After getting the response, I tried this small programme where current time is 14:34:38.899
but at both lines i.e at line 1 and line 2, I got below parsed date
2012-04-10 14:34:38.899
As per reply I should have got 02:34:38.899 at line 1 as date format is yyyy-MM-dd hh:mm:ss.SSS")
java.util.Date date= new java.util.Date();
String strDate=date.toString();
java.util.Date parsedDate;
java.util.Date parsedDate2;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");// line 1
SimpleDateFormat dateFormat2 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");//line 2
try {
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
strDate=timestamp.toString();
parsedDate = dateFormat.parse(strDate);//line1
parsedDate2 = dateFormat2.parse(strDate);//line2
Define your dateFormat like that
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
HH instead of hh. See SimpleDateFormat
Your date format must be yyyy-MM-dd HH:mm:ss.SSS.
hh is hours in am/pm, while HH is hours in a day (that's where you mistake is). See SimpleDateFormat.
As per definition of Date.toString() and Timestamp.toString, the .toString() output is always using a 24-hour clock. If you want to show the time using AM/PM, you should use the dateformatter to print the date. As you are using the same date/time as a source for both (strDate will use 14:34), when you parse the date, the SimpleDateFormat using the 12-hour clock is "lenient" and allows parsing of 14 as an hour.
If you set
dateFormat.setLenient(false);
you'll probably find that the dateFormat.parse(strDate) will fail.
To print dates, I would never rely on toString, but always use a formatter.
System.out.println(dateFormat.format(parsedDate)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate)); // should show ...14:36...
System.out.println(dateFormat.format(parsedDate2)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate2)); // should show ...14:36...
Try below code:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse("yourdate");
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy hh:mm a");String myDate = fmtOut.format(date);
If yourdate is 2016-06-10 12:06:43, then output will be 10-06-2016 12:06 pm.
I have a bit of (Java) that I where I am trying to simply subtract 7 days from the current date. It seemed to me like Calendar.add(..) should be the method to use (and what previous questions here seem to say), so that's what I tried:
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
System.out.println("ReportUtil.getDefaultReportStartDate cal: "+cal.toString() );
System.out.println("PRE ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
cal.add(Calendar.DATE, -7);
System.out.println("POST ReportUtil.getDefaultReportStartDate: "+df.format(cal.getTime()) );
That looks ok to me but you'll see from the output below the month field seems to go a bit... sideways! The day of the month/date seems to change correctly, but what is going on with the month?!
ReportUtil.getDefaultReportStartDate cal: java.util.GregorianCalendar[time=1330098699960,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GB-Eire",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=GB-Eire,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2012,MONTH=1,WEEK_OF_YEAR=8,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=55,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=51,SECOND=39,MILLISECOND=960,ZONE_OFFSET=0,DST_OFFSET=0]
PRE ReportUtil.getDefaultReportStartDate: 24-51-2012
POST ReportUtil.getDefaultReportStartDate: 17-51-2012
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
You get a strange month value because mm means minutes. Try:
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
You can consult the whole list of the format symbols here: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
mm is the format string for Minute. You want MM
Your result seems to be correct.
The month is "1" in both dates of your first log line, which means February.
The "-mm-" in your SimpleDateFormat means minute and not month, thus the odd month of "51"