How does cal.setTime (new Date()); work? - java

I want to use the cal.setTime (new Date()); in my code to update the time, but it dosent work.
import javax.swing.JOptionPane;
public class Exercise2b {
public void demo() {
String message1, message2;
int hour, minute, second;
Time dt = new Time();
hour = dt.getHour();
minute = dt.getMinute();
second = dt.getSecond();
message1 = "The clock is " + minute + " minutes over " + hour + " (+"
+ second + " seconds)";
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message1);
JOptionPane.showMessageDialog(null, message2);
dt.update();
message2 = dt.toString();
JOptionPane.showMessageDialog(null, message2);
}
public static void main(String[] args) {
Exercise2b prog = new Exercise2b();
prog.demo();
}
}
import java.util.Calendar;
import java.util.Date;
public class Time {
private Calendar cal;
private int hour;
private int minute;
private int second;
public Time() {
cal = Calendar.getInstance();
this.hour = cal.get(Calendar.HOUR_OF_DAY);
this.minute = cal.get(Calendar.MINUTE);
this.second = cal.get(Calendar.SECOND);
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public int getSecond() {
return this.second;
}
public String toString() {
return hour + ":" + minute + ":" + second;
}
public void update() {
cal.setTime (new Date());
}
}

I suspect the issue is that you set the cal variable but not the hour/minute/seconds variables that are set from the initial value of `cal in the constructor.
This is an example of DRY (don't repeat yourself). In this situation it's easy to get in an inconsistent state. I would simply have your accessor methods query the cal object directly (instead of using the intermediary variables). And perhaps investigate the Joda library for a better / more reliable date/time API.

The problem is that when you call the update() method you are not refreshing the values of the local variables (second/ minute / hour). Those are already initialized from the constructor.

How does cal.setTime (new Date()); work?
The javadoc states
Sets this Calendar's time with the given Date.
new Date() creates a new Date object with the millisecond value of System.currentTimeMillis().
So
cal.setTime (new Date());
will replace the internal millisecond value of cal to that of the new Date object.

Related

Java Calendar prints only zero

public class JavaCalender {
int hour, minute, second;
public void setCurrent() {
Calendar calendar = new GregorianCalendar();
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return minute;
}
}
class TestJavaCalender {
public static void main(String[] args) {
JavaCalender test = new JavaCalender();
System.out.print(test.getHour() + "\n" + test.getMinute() + "\n" + test.getSecond());
}
}
When I try to run this segment of codes, I could very disappointed, because the result does not equal my expectation. Why the result is all 0, could someone give me an incisive answer and how to use Calendar correctly?
Call the setCurrent(). Its unused for now.
JavaCalender test = new JavaCalender();
test.setCurrent();
System.out.print...
before you print. That's where the values would be set from as per your code.
Edit : Bringing up as mentioned in the comments by #Vikas
Adding to the part Why the result is all 0. Because the default value for primitive ints in Java is 0 and as this answer points test.setCurrent() is never called, so that default value never gets updated.
From your test flow in TestJavaCalender class, you can change your "setCurrent()" method into constructor of JavaCalender class.
orignial:
public void setCurrent() {
Calendar calendar = new GregorianCalendar();
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
after:
public JavaCalender() {
Calendar calendar = new GregorianCalendar();
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
Then, you can use JavaCalender smoothly.

Displaying time elapsed since epoch

I am working on creating a time app that calculates both the current time and the time elapsed since midnight, January 1, 1970, in milliseconds. I went ahead and used Calendar and was able to successfully return the current time but for some reason the elapsed time returns 0. Not sure why that would be.
Here is my current code:
import java.util.Calendar;
import java.util.TimeZone;
public class TimeApp {
public static void main(String[] args) {
Time time1 = new Time();
System.out.println("Hour: " + time1.getHour() + " Minute: " +
time1.getMinute() + " Second: " + time1.getSecond());
Time time2 = new Time();
System.out.println("Elapsed time since epoch: " + time2.getElapsedTime());
}
}
final class Time {
private int hour;
private int minute;
private int second;
private long secondsSinceEpoch;
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
}
public Time(long elapsedTime) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2016, Calendar.SEPTEMBER, 9);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}
#Override
public String toString() {
return hour + ":" + minute + ":" + second;
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return second;
}
public long getElapsedTime() {
return secondsSinceEpoch;
}
}
You aren't setting elapsedTime for time2. I think you wanted
Time time2 = new Time(System.currentTimeMillis());
And as pointed out in the comments, you aren't using elapsedTime in your constructor. Something like
public Time(long elapsedTime) {
secondsSinceEpoch = elapsedTime / 1000;
}
I think you are using the wrong constructor for time2 since you called Time() and this version does not set secondsSinceEpoch. Try using your other constructor Time(long elapsedTime) with any long value and see if it works.
Like this ..
Time time2 = new Time(10000);
Then re-write this constructor since you never use elapsedTime anyway, or delete it completely and re-write the first constructor to assign a value to secondsSinceEpoch.
public Time() {
Calendar calendar = Calendar.getInstance();
this.second = calendar.get(Calendar.SECOND);
this.minute = calendar.get(Calendar.MINUTE);
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
}

Convert a gregorian date to Hijri date using java api

I have jdk java version "1.8.0_45", i am using joda time api (joda-time-2.7.jar)
By using Joda time api i am getting a wrong date.
By using Jdk 8 hijri date api i am getting a correct date.
I have a requirement to convert a gregorian date to hijri date using java api.
My sample test class is as follows:
import org.joda.time.*;
import org.joda.time.chrono.*;
import java.time.*;
import java.time.chrono.HijrahChronology;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTime dtISO = new DateTime();
System.out.println("dtISO = "+dtISO);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance(DateTimeZone.UTC ));
System.out.println(dtIslamic.getYear()+"-" +dtIslamic.getMonthOfYear()+ "-"+ dtIslamic.getDayOfMonth());
java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);
}
}
Output of this class is
C:\>java Test
dtISO = 2015-05-24T09:44:51.704+04:00
1436-8-5
hijradate Hijrah-umalqura AH 1436-08-06
Can you please tell me joda api is correct one or wrong one?
My production server has JDK1.6 i cannot upgrade it to 1.8 as of now, so kindly let me know your suggestions to get a proper hijri date .... Awaiting for your reply....
The difference you are seeing between JodaTime and JDK8 is because they use different implementations of the Hijri Calendar. There are multiple algorithms to compute (approximate) a Hijri date.
Jdk8's HijrahChoronology uses an implementation of Umm-AlQura calendar which closely matches the official Hijri calendar in Saudi Arabia as defined in http://www.ummulqura.org.sa/.
JodaTime IslamicChronology has different implementations which you can select from using its factory methods see http://joda-time.sourceforge.net/apidocs/org/joda/time/chrono/IslamicChronology.html
So it really depends on system audience. If you are in Saudi Arabia or any country which relies on UmmAlQura calendar stick with the JDK8's implementation.
i found this code on http://junaedhalim.blogspot.com/2010/01/hijri-calendar-in-java-using-kuwaiti.html hopefully it help you
import java.util.Calendar;
import java.util.Date;
/**
*
* #author junaed
*/
public class HijriCalendar
{
private int[] userDateG;
private int[] userDateH;
private WaqtMidlet midlet;
private Calendar cal;
private int currentHijriDate;
private int currentHijriMonth;
private int currentHijriYear;
public static final String[] HIJRI_MONTHS =
{
"Muharram", "Safar", "Rabi' al-awwal", "Rabi' al-thani", "Jumada al-awwal",
"Jumada al-thani", "Rajab", "Sha'aban", "Ramadan", "Shawwal", "Dhu al-Qi'dah", "Dhu al-Hijjah"
};
public static final int[] BASE_DATE_G =
{
18, 11, 2009, 0, 0
};
public static final int[] BASE_DATE_H =
{
1, 0, 1431, 0, 0
};
public HijriCalendar(WaqtMidlet midlet)
{
this.midlet = midlet;
cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
}
private void updateDefinedTime()
{
String uTimeH = midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
// String uTimeH = "";
if (uTimeH == null || uTimeH.equalsIgnoreCase(""))
{
userDateG = ApplicationConstants.BASE_DATE_G;
userDateH = ApplicationConstants.BASE_DATE_H;
}
else
{
System.out.println("uTimeH = " + uTimeH);
int date = Integer.parseInt(uTimeH.substring(0, uTimeH.indexOf(';')));
String rest = uTimeH.substring(uTimeH.indexOf(';') + 1);
int month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int hour = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
int minute = Integer.parseInt(rest);
userDateH = new int[]
{
date, month, year, hour, minute
};
// String uTimeG = "";
String uTimeG = midlet.getRmsManager().getString(ApplicationConstants.RMS_GREGORIAN_DATE);
System.out.println("uTimeG = " + uTimeG);
date = Integer.parseInt(uTimeG.substring(0, uTimeG.indexOf(';')));
rest = uTimeG.substring(uTimeG.indexOf(';') + 1);
month = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
rest = rest.substring(rest.indexOf(';') + 1);
year = Integer.parseInt(rest.substring(0, rest.indexOf(';')));
userDateG = new int[]
{
date, month, year, hour, minute
};
}
cal.set(Calendar.HOUR_OF_DAY, userDateG[3]);
cal.set(Calendar.MINUTE, userDateG[4]);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.DATE, userDateG[0]);
cal.set(Calendar.MONTH, userDateG[1]);
cal.set(Calendar.YEAR, userDateG[2]);
currentHijriDate = userDateH[0];
currentHijriMonth = userDateH[1];
currentHijriYear = userDateH[2];
}
private boolean isALeapYear(int year)
{
int modValue = year % 30;
switch (modValue)
{
case 2:
return true;
case 5:
return true;
case 7:
return true;
case 10:
return true;
case 13:
return true;
case 15:
return true;
case 18:
return true;
case 21:
return true;
case 24:
return true;
case 26:
return true;
case 29:
return true;
}
return false;
}
private int getDaysInThisYear(int year)
{
if (isALeapYear(year))
{
return 355;
}
return 354;
}
public int getDaysInThisMonth(int month, int year)
{
if (month % 2 != 0)
{
return 30;
}
else
{
if (month == 12)
{
if (isALeapYear(year))
{
return 30;
}
}
return 29;
}
}
private void addOneDayToCurrentDate()
{
currentHijriDate++;
if(currentHijriDate >= 29)
{
int daysInCurrentMonth = getDaysInThisMonth(currentHijriMonth, currentHijriYear);
if( currentHijriDate > daysInCurrentMonth)
{
currentHijriDate = 1;
currentHijriMonth++;
if(currentHijriMonth > 11)
{
currentHijriMonth = 1;
currentHijriYear++;
}
}
}
}
private void addDays(long days)
{
for(long i = 0; i< days; i++)
{
addOneDayToCurrentDate();
}
}
public String getCurrentDateStr()
{
updateDefinedTime();
Date date = new Date();
// int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
long diff = date.getTime() - cal.getTime().getTime();
long days = diff / (1000 * 86400);
addDays(days);
String ret = currentHijriYear + " "+HIJRI_MONTHS[currentHijriMonth] + ", " + currentHijriDate;
return ret;
// return midlet.getRmsManager().getString(ApplicationConstants.RMS_HIJRI_DATE);
}
}
Try using ICU4J. Its Calendar classes do not extend java.util.Calendar, but they do properly deal with Hijri dates (and many other calendar systems). I was able to get what I believe are correct results using its IslamicCalendar class, using Java 1.6.0_31:
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.IslamicCalendar;
public class HijriDate {
public static void main(String[] args) {
java.util.Calendar gregorianCal =
java.util.Calendar.getInstance(Locale.US);
System.out.printf("%tF%n", gregorianCal);
Date date = gregorianCal.getTime();
Calendar cal = new IslamicCalendar();
cal.setTime(date);
System.out.printf("%02d-%02d-%02d%n",
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH));
}
}

JSpinner time constraint

I am trying to create a spinner that has hours and minutes. The minutes part needs to increment by 10 mins only and the time must range from the current time to an end time. I also need the minimum value (previously current time) to update to current time.
I tried playing around with it, but I just couldn't get it to work.
JSpinner spinner1 = new javax.swing.JSpinner();
SpinnerDateModel spinnermodel = new SpinnerDateModel();
spinnermodel.setCalendarField(Calendar.MINUTE);
spinner1.setModel(spinnermodel);
spinner1.setEditor(new JSpinner.DateEditor(spinner1, "hh:mm"));
SpinnerModel model = new SpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE * 10 ?);
The SpinnerDateModel just uses 1 to increment the field you want to change.
I extended the SpinnerDateModel to add an addition property to the model to control the increment value instead of hard coding to 1:
import java.util.*;
import javax.swing.*;
public class MySpinnerDateModel extends SpinnerDateModel
{
private int increment = 1;
public MySpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField)
{
super(value, start, end, calendarField);
}
public MySpinnerDateModel()
{
this(new Date(), null, null, Calendar.DAY_OF_MONTH);
}
public void setIncrement(int increment)
{
this.increment = increment;
}
public int getIncrement()
{
return increment;
}
#Override
public Object getNextValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), increment);
Date next = cal.getTime();
Comparable end = getEnd();
return ((end == null) || (end.compareTo(next) >= 0)) ? next : null;
}
#Override
public Object getPreviousValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), -increment);
Date prev = cal.getTime();
Comparable start = getStart();
return ((start == null) || (start.compareTo(prev) <= 0)) ? prev : null;
}
}
You should be able to use the model the way you did before but with one additional statement:
MySpinnerDateModel model = new MySpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE);
model.setIncrement( 10 );
You can extend the SpinnerDateModel to specify the behavior. Below is an example in which the getNextValue and getPreviousValue are overridden to return values +/- 10 minutes:
Date now = new Date();
Date start = now;
final long tenMinutesInMillis = 1000 * 60 * 10;
Date end = new Date(now.getTime() + tenMinutesInMillis * 60);
SpinnerModel model = new SpinnerDateModel(now, start, end, Calendar.MINUTE){
#Override
public Object getNextValue(){
Date newDate = new Date(getDate().getTime() + tenMinutesInMillis);
Date endDate = (Date)getEnd();
return newDate.getTime() > endDate.getTime() ? endDate : newDate;
}
#Override
public Object getPreviousValue(){
Date newDate = new Date(getDate().getTime() - tenMinutesInMillis);
Date startDate = (Date)getStart();
return newDate.getTime() < startDate.getTime() ? startDate : newDate;
}
};

Android - Java - Get Access to TimePickerDialog

Hi I currently have a TimePickerDialog:
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet( TimePicker view, int hourOfDay, int minute ) {
c.set( Calendar.HOUR_OF_DAY, hourOfDay );
c.set( Calendar.MINUTE, minute );
String hour = Integer.toString(hourOfDay);
String min = Integer.toString(minute);
String timeStamp = hour + ":" + min;
}
};
However I just want to know how can I gain access to the TimeStamp String outside of the method ? As I need to use it again to send it into another method which inputs it into a JSON Object. I did try making the String Final or Public but just got errors.
Just make a field to the class named timeStamp and change it.
Example:
public class Outside
{
private String timeStamp;
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet( TimePicker view, int hourOfDay, int minute ) {
c.set( Calendar.HOUR_OF_DAY, hourOfDay );
c.set( Calendar.MINUTE, minute );
String hour = Integer.toString(hourOfDay);
String min = Integer.toString(minute);
timeStamp = hour + ":" + min;
}
};
}
I removed String timeStamp "String" because you now refer to the field.
Now timeStamp will contains hour + ":" + min when onTimeSet is called.
P.S You cannot make it final since it will change everytime onTimeSet is called.

Categories