I have String initialTime= "10:30:00"
I am converting it into time like so:-
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Time time = new Time(date.getTime());
int initHour = time.getHours()
int initMind = time.getMinutes();
Further I have two values;
int hour, mins;
The hour value can be anything from 0-10;
mins value can be 0,15,30,45.
The user selects a time by selecting hour and mins. As soon as the user selects the values they should get added to the initialTimeand shown in finalTIme
So if:-
hour=0 and mins=15 then finalTIme=10:45:00
hour=0 and mins=35 then finalTIme=11:00:00
hour=0 and mins=45 then finalTIme=11:15:00
I tried doing something like:-
if(hour==0 && mins==0)
{
finalTime = initialTime;
}
else if(hour==0 && mins>0 && mins <30)
{
mins = initMins + mins
}
else if(hour==0 && mins>0 && mins >=30)
{
hours = hours+1;
mins = mins-60;
}
But I did not get the required output. HOw can I do it in a less complicated manner?
You can use java.util.Calendar class:
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
date = cal.getTime();
You might also consider the new Date API from JDK 8.
Related
I'm trying to create a method that prints e.g. actual time of arrival (now) and then it prints the time of departure which I want to set plus 3 minutes compared to the first one.
public void updateTimes(){
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
this.arrivalTime = new Date();
this.departureTime = this.arrivalTime.plusMinutes(3);
}
Departure time doesn't work as intended.
Any help is welcome.
java.util.Date not have plusMinutes.
It can be better if you use Java 8, with java.time library :
LocalTime arrivalTime = LocalTime.now();//Current time
LocalTime departureTime = arrivalTime.plusMinutes(3);//plus 3 minutes to the time
//Then you can format the time
String result = departureTime.format(DateTimeFormatter.ofPattern("H:mm"));
Another solution using Calendar looks like:
Calendar cal = Calendar.getInstance();
cal.setTime(arrivalTime); // only if different from "now"
cal.add(Calendar.MINUTE, 3);
departureTime = cal.getTime();
I think you can do something like below:
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
Date date = new Date();
System.out.println("arrival time = " + sdf.format(date));
int min = date.getMinutes();
date.setMinutes(min+3);
System.out.println("departure time = " + sdf.format(date));
I want to set a boolean value isBasePriceTime to false if the current time is equal to 6pm or after 6pm and is not between midnight and 6am the next day. However it keeps setting the isBasePriceTime to false if the current time of the day is for example 2pm.
private boolean checkCurrentTimePriceType()
{
/*Get the current price type depending on the time of the day the user wants to
get a cab */
Calendar today = Calendar.getInstance();
Date currentDate = today.getTime();
//creates a time for 6pm
String nightPriceFullTime = "18:00:00";
Date nightPriceTime = java.sql.Time.valueOf(nightPriceFullTime);
Calendar nightPriceDateCalendar = Calendar.getInstance();
nightPriceDateCalendar.setTime(nightPriceTime);
//creates a time for midnight
String nightPriceFullTimeMidnight = "00:00:00";
Date nightPriceTimeMidnight = java.sql.Time.valueOf(nightPriceFullTimeMidnight);
Calendar nightPriceMidnightDateCalendar = Calendar.getInstance();
nightPriceMidnightDateCalendar.setTime(nightPriceTimeMidnight);
//creates a time for 6am
String basePriceFullTime = "06:00:00";
Date basePriceTime = java.sql.Time.valueOf(basePriceFullTime);
Calendar basePriceDateCalendar = Calendar.getInstance();
basePriceDateCalendar.setTime(basePriceTime);
boolean isBasePriceTime;
//checks if the current time is or after 6pm, or if the the current time is between midnight and 6am
if(((today.getTime().after(nightPriceDateCalendar.getTime())) || (today.getTime().equals(nightPriceDateCalendar.getTime())))
|| ((today.getTime().before(basePriceDateCalendar.getTime())) && (today.getTime().after(nightPriceMidnightDateCalendar.getTime()))))
{
//user will pay a night time price
isBasePriceTime = false;
}
else
{
//user will pay a base time price
isBasePriceTime = true;
}
//return value of isNightPrice boolean variable
return isBasePriceTime;
}
Maybe this simplification will work for you:
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); //Current hour
return currentHour < 18 //False if after 6pm
Using Jodatime:
LocalTime time = new LocalTime(/* Optional but recommended: specify timezone */);
return time.isAfter(LocalTime.of(18, 0))
|| time.isBefore(LocalTime.of(6, 0));
Using Java 8:
LocalTime time = LocalTime.now(/* Optional but recommended: specify timezone */);
return time.isAfter(LocalTime.of(18, 0))
|| time.isBefore(LocalTime.of(6, 0));
(Note that the class names are the same, but they are from different packages).
java.sql.Time.valueOf(nightPriceFullTime) will return January 1, 1970 18:00:00. You should use some other way to convert the Strings into dates. If you want to keep using this conversion method, you will have to change how you compare the time of the different calendars. For example:
if(nightPriceDateCalendar.get(Calendar.HOUR_OF_DAY) > today.get(Calendar.HOUR_OF_DAY) && ...){...}
Another approach will be this:
String time = "18:00:00";
SimpleDateFormat sdf = SimpleDateFormat("yyyy/MM/dd");
String onlyDate = sdf.format(new Date());
sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dateAndTime = sdf.parse(onlyDate+" "+time);
Calendar nightPriceDateCalendar = Calendar.getInstance();
nightPriceDateCalendar.setTime(dateAndTime);
I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.
I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getTimeInstance();
int i = 0;
for (DataPoint dp : dataSet.getDataPoints()) {
for(Field field : dp.getDataType().getFields()) { //loop 7 times
int test = dp.getValue(field).asInt();
String weekSteps= String.valueOf(test); //get weekday steps one at a time
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Calendar cal = Calendar.getInstance();
String weekday = sdf.format(cal.getTime());
String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day
FeedItem item = new FeedItem();
item.setTitle(weekStepsFinal);
feedItemList.add(item);
}
}
}
There are 7 datasets btw.
If by "take away one day at a time" means that you want the days going backwards, then here's how:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println("Last 7 days (starting today):");
Calendar cal = Calendar.getInstance(); // Initialized to today/now
for (int i = 0; i < 7; i++) {
System.out.println(" " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
}
OUTPUT
Last 7 days (starting today):
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
This will subtract 7 days from the calendar to get you the date 7 days ago:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7).
To subtract one day use the following code :
int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Date currentDate = new Date();
long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String day = sdf.format(previousDay);
I try to subtract one day when the time inside 0:00 am - 12:00 am.
ex: 2012-12-14 06:35 am => 2012-12-13
I have done a function and It's work. But my question is any other better code in this case? Much simpler and easy to understand.
public String getBatchDate() {
SimpleDateFormat timeFormatter = new SimpleDateFormat("H");
int currentTime = Integer.parseInt(timeFormatter.format(new Date()));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
String Date = dateFormatter.format(new Date());
if ( 0 <= currentTime && currentTime <= 12){
try {
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(dateFormatter.parse(Date));
shiftDay.add(Calendar.DATE, -1);
Date = dateFormatter.format(shiftDay.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("BatchDate:", Date);
}
return Date;
}
THANKS,
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(new Date())
if(shiftDay.get(Calendar.HOUR_OF_DAY) <= 12){
shiftDay.add(Calendar.DATE, -1);
}
//your date format
Use the Calendar class to inspect and modify the Date.
Calendar cal = new GregorianCalendar(); // initializes calendar with current time
cal.setTime(date); // initializes the calender with the specified Date
Use cal.get(Calendar.HOUR_OF_DAY) to find out the hour within the day.
Use cal.add(Calendar.DATE, -1) to set the date one day back.
Use cal.getTime() to get a new Date instance of the time that was stored in the calendar.
As with nearly all questions with regard to Date / Time, try Joda Time
public String getBatchDate() {
DateTime current = DateTime.now();
if (current.getHourOfDay() <= 12)
current = current.minusDays(1);
String date = current.toString(ISODateTimeFormat.date());
Log.d("BatchDate:" + date);
return date;
}
I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();