Android Studio: Bug with Calendar.DAY_OF_WEEK - java

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();
}

Related

Wrong value of Days between two Dates

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);
}

How can I setMaxDate() for DatePicker to one month after the current date?

Here's my onCreateDialog:
DatePickerDialog dialog = new DatePickerDialog(this, dpickerListener, year_x, month_x, day_x);
dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
dialog.getDatePicker().setMaxDate();
As you can see, setMaxDate() is empty. I want to set the max date of the datePickerDialog to one month after the current date.
Here's how I get the current date:
cal2 = Calendar.getInstance();
currentDay = cal2.get(Calendar.DAY_OF_MONTH);
currentMonth = cal2.get(Calendar.MONTH);
currentYear = cal2.get(Calendar.YEAR);
currentDate = new Date();
currentDate.setDate(currentDay);
currentDate.setMonth(currentMonth);
currentDate.setYear(currentYear);
Use this snippet
Calendar cal=Calendar.getInstance()
cal.add(Calendar.MONTH,1)
long afterTwoMonthsinMilli=cal.getTimeInMillis()
DatePickerDialog.getDatePicker().setMaxDate(afterTwoMonthsinMilli);
It reads the current system date into a calendar object and adds 1 to the specified field,In this case MONTH and returns a calendar object
Similarly if you want to add values to other fields,Specify the field in the field type as:
Calendar.DAY_OF_MONTH
Calendar.YEAR
Calendar.HOUR
etc.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis);
You can use "add" to add to the Calendar.MONTH
you have to override OnDateChangedListener
`new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year,
int month, int day) {
Calendar newDate = Calendar.getInstance();
newDate.add(Calendar.MONTH, 1);
if (calendar.before(newDate)) {
view.init(minYear, minMonth, minDay, this);
}
}
});`

Subtract one Day from date when inside a time interval

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;
}

Formatting date and time

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.

getdate from datepicker android

I want to get date from datepicker widget in android I have tried with this
Date date1= (Date) new Date
(dpBirthDate.getYear(), dpBirthDate.getMonth(), dpBirthDate.getDayOfMonth());
date1 = (Date) new SimpleDateFormat("yyyy-MM-dd").parse(date1.toString());
But I get a date like this mon 7 dec 2011 time ... and all I want to get is the yyyy-MM-dd format to store it in the database.
I tried also to concat the year-month-day like this but the problem is for example today
2011-12-7 the day should be 07 to be valid
Could you help me please.
I use this:
/**
*
* #param datePicker
* #return a java.util.Date
*/
public static java.util.Date getDateFromDatePicker(DatePicker datePicker){
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar.getTime();
}
You should use SimpleDateFormat.format to convert that Date object to a String, like this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(date1);
I think you just had it backwards. You need to use format to go from Date to String, and parse to go from a String to a Date.
I know this is old but i struggled to find it. So for posterity
Scenario: A View needs the date in yyyy-mm-dd
date_field = (EditText)findViewById(R.id.input_date);
date_field.setFocusable(false); // disable editing of this field
date_field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
chooseDate();
}
});
private void chooseDate() {
final Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePicker =
new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(final DatePicker view, final int year, final int month,
final int dayOfMonth) {
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
calendar.set(year, month, dayOfMonth);
String dateString = sdf.format(calendar.getTime());
date_field.setText(dateString); // set the date
}
}, year, month, day); // set date picker to current date
datePicker.show();
datePicker.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
dialog.dismiss();
}
});
}
Hope this helps someone
If your formatting was simple as numbers,
eg: dd/MM/yyyy
You can use the Kotlin way:
val dp = binding.datePicker
val date = "${dp.dayOfMonth.let { if(it < 10) "0$it" else it }}/${dp.month.plus(1).let { if(it < 10) "0$it" else it }}/${dp.year}"

Categories