I want to print and update the date and time simultaneously. The following code only takes the time once and prints the same time 40 times. How can I update the time while printing it?
public class Dandm {
public static void main(String args[]) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String time = df.format(date);
int i;
for (i = 40; i > 0; i--) {
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
}
}
Replace System.out.println(date); with System.out.println(new Date());
The problem is, when you do Date date = new Date(); then date value doesn't change in the loop. You need a new date every time, so you should create a new Date() object every time.
Edit based on the comments (To get date as a string with only time):
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
for(i = 40; i > 0; i--){
Date date = new Date();
String str = sdf.format(date);
System.out.println(str);
try{Thread.sleep(500);}
catch (InterruptedException e){}
}
You are creating your object one time only, once your object is created it acquires its properties:
Date date = new Date();
If you want to update your time along side printing it, then either you would create the object within the loop like this:
for (i = 40; i > 0; i--) {
Date date = new Date();
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
Or just create an anonymous Date object in the print function.
for (i = 40; i > 0; i--) {
System.out.println(new Date());
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
Related
public class test {
public static void check1 (String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
if(date.matches("^\\w+.+")) {
Date date1 = sdf2.parse(date);
}
else {
Date date1 = sdf1.parse(date);
}
Date current = new Date();
if(date1.compareTo(current)<-1) {
System.out.println("In Past");
}
else {
System.out.println("Same or future date");
}
How can I use the updated value of date1 in second if block.
A variable is only visible within the scope it is declared (between it's enclosing { and } ).
Your 2 date1 variables are declared (Date date1) within the scope of the if and the else blocks. Therefore they are not visible outside (they effectively don't exist outside of those scopes).
You need to declare it outside:
public static void check1(String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1; // <- declare date1 here
if (date.matches("^\\w+.+")) {
date1 = sdf2.parse(date);
} else {
date1 = sdf1.parse(date);
}
Date current = new Date();
if (date1.compareTo(current) < -1) {
System.out.println("In Past");
} else {
System.out.println("Same or future date");
}
}
You have declared your variable in a scope, which is ending when you close your bracket, aka it is no longer alive after that. What you could do is you can take it out:
public static void check1 (String date) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1;
if(date.matches("^\\w+.+")) {
date1 = sdf2.parse(date);
}
else {
date1 = sdf1.parse(date);
}
Date current = new Date();
if(date1.compareTo(current)<-1) {
System.out.println("In Past");
}
else {
System.out.println("Same or future date");
}
}
I am trying to get date in my database that have format like this "dd/MM/yyyy" and compare them to get latest date..
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me. Any suggestions? It seems like this should be an easy feat to accomplish.
from String last_updatedArr[]'s array result :
12/11/2015
12/11/2015
12/11/2015
12/11/2015
12/11/2015
13/11/2015
Method:
public String latestDate(){
String last_updated=null;
try {
String last_updatedDb=null;
String query = "SELECT Last_updated FROM Mattress";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs= pst.executeQuery();
String last_updatedArr[]=new String[100];
while(rs.next()){
int i = 0;
last_updatedDb=rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i]=last_updatedDb;
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
for(int i =0;i<last_updatedArr.length;i++){
date1 = (java.sql.Date)sdf.parse(last_updatedArr[i]);
date2 = (java.sql.Date)sdf.parse("1/1/2010");
if(date1.after(date2)){
//Date1 is after Date2
last_updated= sdf.format(date1);
}
if(date1.before(date2)){
//Date1 is before Date2
last_updated= sdf.format(date2);
}
if(date1.equals(date2)){
//Date1 is equal Date2
last_updated= sdf.format(date1);
}
}
} catch (ParseException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return last_updated;
}
Your loop resets i on every iteration. Move the declaration of i in your while loop. Or just use a for loop. Like,
for(int i = 0; rs.next(); i++) {
last_updatedDb = rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i] = last_updatedDb;
}
or something like,
int i = 0;
while(rs.next()){
// int i = 0;
last_updatedArr[i] = rs.getString("Last_updated");
System.out.println(last_updatedArr[i]);
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
// reuse i from while loop...
for(i = 0; i < last_updatedArr.length; i++){
I would like to compare a Date I get from my local machine to an integer I get from a scanner. The date is formated as: MMDDYYYY such as 11232015 which is todays date. My integer is then 11192015. I want to convert my date to an integer and then compare the true date vs. the one I got from my scanner:
Calendar c;
DateFormat df = new SimpleDateFormat("MMddyyyy");
c.getInstance();
Date currentDate = c.getTime();
int dateFromScanner = 11192015;
Date formattedDate = df.format(currentDate);
if (dateFromScanner !> formattedDate {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
But I cannot compare dates to integers.
You can do something like that:
DateFormat df = new SimpleDateFormat("MMddyyyy");
Date currentDate = new Date();
int dateFromScanner = 11192015;
try {
Date formattedDateFromScanner = df
.parse(String.valueOf(dateFromScanner));
if (formattedDateFromScanner.before(currentDate)) {
// Do some stuff
} else {
System.out.println("This date has not yet passed.");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try a solution like this, it can give you some idea what do you do.
public static void main(String[] args) {
Calendar c = null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter date value like yyyyMMdd.");
int dat = sc.nextInt();
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date currentDate = c.getInstance().getTime();
String formattedDate = df.format(currentDate);
System.out.println(formattedDate);
if (dat < Integer.parseInt(formattedDate)) {
System.out.println("This date had being passed.");
} else {
System.out.println("This date has not yet passed.");
}
}
Hello everyone i try to check between days two daytimes
i have for example 12/10/2014 and 12/15/2015 datetimes.I wrote some code witch can to check different days between there two daytimes
this is a my source
public String getDateDiffString(Date dateOne, Date dateTwo) {
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return String.valueOf(delta);
} else {
delta *= -1;
return String.valueOf(delta);
}
}
this code working perfect but i want to increase days for example 12/10/2014, 12/11,2014.....12/20/2014 between first and second daytimes.i i also wrote code but result is between first date and second days -1(between 12/19/2014)
this is a my source
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date _d;
try {
SimpleDateFormat new_df = new SimpleDateFormat("d MMM");
_d = df.parse(timeInfo.getTimeformat().get(0));
Date _d1 = df.parse(timeInfo.getEndTimeFormat().get(0));
String datetimeis = getDateDiffString(_d1, _d);
int differentdays = Integer.parseInt(datetimeis);
Log.e("Different is ", "" + differentdays);
for (int k = 0; k < differentdays; k++) {
String datetimeformat = dateFormatter(timeInfo.getStartTimePeriod().get(0));
Date datetime = new_df.parse(datetimeformat);
Calendar cal = Calendar.getInstance();
cal.setTime(datetime);
cal.add(Calendar.DATE, k);
datetime = cal.getTime();
String ttime = new_df.format(datetime);
ApishaDaysAdapter.add(ttime);
ApishaHollsAdapter.add(timeInfo.getHole());
String start_time = timeInfo.getTime();
start_time = start_time.replace(",", "\n");
ApishaTimesAdapter.add(start_time);
timeInfo.setStartTimePeriod(ttime);
System.out.println(ttime);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
how i can solve my problem?if anyone knows solution please help me
i want to increase days [12 -20] and not [12-19)
I am trying to remove data from hashtable for a particular date,the hashtable is of type (String,vector).Initially i am checking if hashtable contains the usrDate if yes then i need to remove all the data frm hashtable only for usrDate and add the new data that is listEvents.But the contains from hashtable for other dates should not be deleted.
listEvents.addElement(eventBean);//new data is here
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
}
//checking if hashtable has given date
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector)listUserEvents.get(usrDate);
info.addElement(eventBean);
listUserEvents.put(usrDate,info);
} else {
listUserEvents.put(usrDate,listEvents);
}
i just want to add listEvents to the hashtable for the given date,without affecting the other data in hashtable which has data for some other dates.
private Hashtable getEvents(String usrDate, String timezone) {
try {
listUserEvents = getUserInfo();
listEvents = new Vector();
Calendar calendarLocalEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEvent = calendarLocalEvent.getTimeZone();
System.out.println("Time Zone first-->"
+ timeZoneEvent.getDefault());
if (timezone.equals(timeZoneEvent.getDefault())) {
;
} else {
TimeZone timeZoneChange = TimeZone.getTimeZone(timezone);
System.out.println("Time Zone change-->" +timeZoneChange);
Device.setTimeZone(timeZoneChange);
}
EventList eventList = (EventList) PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START)
&& event.countValues(Event.START) > 0)
{
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd,yyyy HH:mm");
SimpleDateFormat sdf_start = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdf_start_min = new SimpleDateFormat("HH");
String dateString = sdf.formatLocal(start);
String timeString = sdf_start.formatLocal(start);
String hour = sdf_start_min.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" + date +"user" + usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventData eventBean = new EventData();
if (eventList.isSupportedField(Event.END)
&& event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat(
"MMM dd, yyyy HH:mm");
SimpleDateFormat sdfTime = new SimpleDateFormat(
"HH:mm");
SimpleDateFormat sdfhr = new SimpleDateFormat("HH");
String dateString1 =sdform.formatLocal(end);
String timeString1 =sdfTime.formatLocal(end);
String hr = sdfhr.formatLocal(end);
eventBean.setStartHr(hour);
eventBean.setEndHr(hr);
eventBean.setStartTime(timeString);
eventBean.setEndTime(timeString1);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
// Dialog.alert("equal startdate" + dateString);
// Dialog.alert("equal end date"+ dateString1);
}
if (eventList.isSupportedField(Event.LOCATION)
&& event.countValues(Event.LOCATION) > 0) {
String location = event
.getString(Event.LOCATION, 0);
eventBean.setLocation(location);
// Dialog.alert("equal location"+ location);
}
if (eventList.isSupportedField(Event.SUMMARY)
&& event.countValues(Event.SUMMARY) > 0) {
String subject = event.getString(Event.SUMMARY, 0);
eventBean.setSummary(subject);
// Dialog.alert("equal subject" +subject);
}
eventBean.setUserDate(usrDate);
eventBean.setTimeZone(timezone);
listEvents.addElement(eventBean);
System.out.println("the size bf hashis"
+ listEvents.size());
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
System.out.println("so thesummary is ::"
+ e.getSummary());
}
// for(int i=0;i<listUserEvents.size();i++){
if (listUserEvents.containsKey(usrDate)) {
// listUserEvents.remove(usrDate);
Vector info = (Vector)listUserEvents.get(usrDate);
System.out.println("the size in getEvents is"
+ info.size());
if(info.contains(usrDate)){
System.out.println("in info");
}
info.addElement(eventBean);
System.out.println("vector size info is"
+ info.size());
listUserEvents.put(usrDate,info);
} else {
System.out.println("in else of getevent" +listEvents.size());
listUserEvents.put(usrDate,listEvents);
}
// }
} else {
// Dialog.alert("not equal");
}
}
}
Device.setTimeZone(timeZoneEvent);
Calendar calendarLocalLastEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEventLast =calendarLocalLastEvent.getTimeZone();
System.out.println("Time Zone last-->"
+ timeZoneEventLast.getDefault());
} catch (PIMException e) {
// //Dialog.alert(e.getMessage());
}
System.out.println("size in hashtable " + listUserEvents.size());
return listUserEvents;
}
It must be something like this
for(int i = 0; i<listUserEvents.size();i++)
{
if (listUserEvents.containsKey(usrDate)){
listUserEvents.remove(usrDate);
}
}
Here is a simple example of how this works:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
if (numbers.containsKey("two")) {
numbers.put("two", 222);
}
What are you having difficulty at? Moreover what is the type of your Hashtable key? Is it java.util.Date or something else?