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;
}
Related
I'm trying to count the days between two dates but I can't get a right result.
I did the same that someone described to me.
My result should be an int or long. For this example I would expext 11 but 10 is also fine.
That's the code:
String startDate = "2018-03-25";
String endDate = "2018-04-05";
Date startDate1 = stringToDate(startDate);
Date endDate1 = stringToDate(endDate);
long ab = daysBetween(startDate1, endDate1);
String ab1 = String.valueOf(ab);
And that's the methods:
public static long daysBetween(Date startDate, Date endDate) {
Calendar sDate = getDatePart(startDate);
Calendar eDate = getDatePart(endDate);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
public Date stringToDate(String stringDatum) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(stringDatum);
return date;
}
catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millisecond in second
return cal; // return the date part
}
java.util.Date, Calendar and SimpleDateFormat are part of a terrible API. They make the job of date/time handling harder than it already is.
Make yourself a favor and use a decent date/time library: https://github.com/JakeWharton/ThreeTenABP - here's a nice tutorial on how to use it - How to use ThreeTenABP in Android Project
With this API, it's so easy to do what you want:
LocalDate startDate = LocalDate.parse("2018-03-25");
LocalDate endDate = LocalDate.parse("2018-04-05");
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); // 11
I've chosen to use LocalDate based on your code: the inputs have only day, month and year, and you're setting the hour/minute/seconds to zero, so I understand that you don't care about the time of the day to calculate the difference - which makes LocalDate the best choice.
Date and Calendar represent a specific point in time, and Calendar also uses a timezone, so Daylight Saving changes might affect the results, depending on the device's default timezone. Using a LocalDate avoids this problem, because this class doesn't have a timezone.
But anyway, I've tested your code and also got 11 as result, so it's not clear what problems you're facing.
private static long daysBetween(Date date1, Date date2){
return (date2.getTime() - date1.getTime()) / (60*60*24*1000);
}
I have a string in format :
2015-10-01 02:00
I want to print the remaining time compared to current time in Java, it should print in format :
It remains 1 day 4 hours 25 minutes
How could I do that ? Thanks for any ideas.
I got it working! Could you withdraw all the unvotes please ?
public static void calculateRemainTime(String scheduled_date){
// date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// two dates
java.util.Date scheduledDate;
Calendar current = Calendar.getInstance();
java.util.Date currentDate;
String current_date = format.format(current.getTime());
try {
scheduledDate = format.parse(scheduled_date);
currentDate = format.parse(current_date);
long diffInMillies = scheduledDate.getTime() - currentDate.getTime();
long diffence_in_minute = TimeUnit.MINUTES.convert(diffInMillies,TimeUnit.MILLISECONDS);
System.out.println(diffence_in_minute);
} catch (ParseException e) {
e.printStackTrace();
}
}
I didn't found my "bug" in another question, so I really need help.
In my app, I have this code:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.MONTH);
calendar.set(Calendar.YEAR, Calendar.YEAR);
calendar.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH);
calendar.set(Calendar.HOUR_OF_DAY, Calendar.HOUR);
calendar.set(Calendar.MINUTE, Calendar.MINUTE);
calendar.set(Calendar.SECOND, Calendar.SECOND);
frase(calendar);
This code is inside onCreate and the code below is below onCreate();
public void frase(Calendar calendar)
{
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.MONDAY:textView.setText(getText(R.string.segunda));break;
case Calendar.TUESDAY:textView.setText(getText(R.string.terca));break;
case Calendar.WEDNESDAY:textView.setText(getText(R.string.quarta));break;
case Calendar.THURSDAY:textView.setText(getText(R.string.quinta));break;
case Calendar.FRIDAY:textView.setText(getText(R.string.sexta));break;
case Calendar.SATURDAY:textView.setText(getText(R.string.sabado));break;
case Calendar.SUNDAY:textView.setText(getText(R.string.domingo));break;
}
}
When I run the app, my emulator always returns me the Saturday case but the emulator day of the week is wednesday.
The second argument to Calendar.set() is the value you want to that particular field defined by the first argument. Now you're setting constant values i.e. field index numbers, which makes no sense.
Remove your set() calls altogether. Calendar.getInstance() already returns an instance that is initialized to current date and time.
Get Date
public static String getDate() {
Date myDate = new Date();
String date = new SimpleDateFormat("yyyy-MM-dd").format(myDate);
// new SimpleDateFormat("hh-mm-a").format(myDate);
return date;
}
Get day of week
public static int dayOfWeek(String date) {
try {
int day = 0;
SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy-MM-dd");
Date now = simpleDateformat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return day;
} catch (Exception e) {
return null;
}
}
Or simply call
getDay(new Date());
public static String getDay(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
//System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
return simpleDateFormat.format(date).toUpperCase();
}
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.
I have a question related to conversion/formatting of date.
I have a date,say,workDate with a value, eg: 2011-11-27 00:00:00
From an input textbox, I receive a time value(as String) in the form "HH:mm:ss", eg: "06:00:00"
My task is to create a new Date,say,newWorkDate, having the same year,month,date as workDate,and time to be the textbox input value.
So in this case, newWorkDate should be equal to 2011-11-27 06:00:00.
Can you help me figure out how this can be achieved using Java?
Here is what I have so far:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
//Text box input is converted to Date format -what will be the default year,month and date set here?
Date textBoxTime = df.parse(minorMandatoryShiftStartTimeStr);
Date workDate = getWorkDate();
int year = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(0, 4));
int month = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(4, 6));
int date = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(6, 8));
Date newWorkDate = DateHelper.createDate(year, month, day);
//not sure how to set the textBox time to this newWorkDate.
[UPDATE]: Thx for the help,guys!Here is the updated code based on all your suggestions..Hopefully this will work.:)
String[] split = textBoxTime.split(":");
int hour = 0;
if (!split[0].isEmpty)){
hour = Integer.parseInt(split[0]);}
int minute = 0;
if (!split[1].isEmpty()){
minute = Integer.parseInt(split[1]);}
int second = 0;
if (!split[2].isEmpty()){
second = Integer.parseInt(split[2]);}
Calendar cal=Calendar.getInstance();
cal.setTime(workDate);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
Date newWorkDate = cal.getTime();
A couple of hints:
Use a Calendar object to work with the dates. You can set the Calendar from a Date so the way you create the dates textBoxTime and workDate are fine.
Set the values of workDate from textBoxTime using the setXXX methods on Calendar class (make workDate a Calendar)
You can use SimpleDateFormat to format as well as parse. Use this to produce the desired output.
You should be able to do this with no string parsing and just a few lines of code.
Since you already have the work date, all you need to do is convert your timebox to seconds and add it to your date object.
Use Calendar for date Arithmetic.
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
Date desiredDate = cal.getTime();
You may need the following code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date workDate = simpleDateFormat1.parse("2011-11-27");
Calendar workCalendar= Calendar.getInstance();
workCalendar.setTime(workDate);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.setTime(simpleDateFormat2.parse("06:00:00"));
workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
Date newWorkDate = workCalendar.getTime();
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
System.out.println(simpleDateFormat3.format(newWorkDate));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this would help you.