Getting day of week based on date provided - android

The following code sometimes give correct output And sometimes gives wrong
For example :
7th april 1990 returns Monday which is correct
31st dec 1987 returns Sunday which is incorrect, it should be Tuesday
I have tried:
int mm=Integer.parseInt(m);
GregorianCalendar calendar = new GregorianCalendar(Integer.parseInt(y),mm,Integer.parseInt(d));
int i = calendar.get(Calendar.DAY_OF_WEEK);
String dayOfTheWeek = null;
if(i == 2){
dayOfTheWeek = "Monday";
} else if (i==3){
dayOfTheWeek = "Tuesday";
} else if (i==4){
dayOfTheWeek = "Wednesday";
} else if (i==5){
dayOfTheWeek = "Thursday";
} else if (i==6){
dayOfTheWeek = "Friday";
} else if (i==7){
dayOfTheWeek = "Saturday";
} else if (i==1){
dayOfTheWeek = "Sunday";
}
Log.v("Event Week",Integer.toString(i));
return dayOfTheWeek;

GregorianCalendar calendar = new GregorianCalendar(1987, 11, 31);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
Gives output as Saturday
and
GregorianCalendar calendar = new GregorianCalendar(1990, 3, 7);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
Gives output as Thursday
Which matches what the calendar shows.
Note: The month field is 0-index based. So, January is 0, and December is 11.
PS: The actual output to the above code is an integer. So, you will need to check the values and figure out the DAY.

I managed to solve my problem
The following code gives
1.Day of week based on birthdate of the coming birthday
2.Also tested with leap year Feb 29, works perfect
int checkFutureLeapYear=0;
Calendar today=Calendar.getInstance();
Calendar BDay=Calendar.getInstance();
int CYear=today.get(Calendar.YEAR);
// checking whether entered date contains Feb 29 ,if yes check whether //current year is leap years so that it can handle 29
if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
// if leap year leave the date as it as , since it can handle 29
if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
d=d;
}
// if not subtract 1 from date , to make it 28 , as current year donot contains feb 29 ,so making it feb 28
else {
int date=Integer.parseInt(d);
date=(date-1);
d=Integer.toString(date);
}
}
String startDate=y+"/"+m+"/"+d;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Date date=null;
try{
date=sdf.parse(startDate);
}
catch (Exception e) {
e.printStackTrace();
}
BDay.setTime(date);
int BMonth=BDay.get(Calendar.MONTH);
int BDate=BDay.get(Calendar.DATE);
int CMonth=today.get(Calendar.MONTH);
int CDate=today.get(Calendar.DATE);
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR));
// if current month is greater than birth month , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
if (BMonth<CMonth) {
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
checkFutureLeapYear=1;
}
// Also if current month and birth month are same , but current date is greater than birth date , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
else if ((BMonth==CMonth)&&(BDate<CDate)) {
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
checkFutureLeapYear=1;
}
// code to check that ,is the future year can handle feb 29, same as above conditions
if (checkFutureLeapYear==1) {
CYear=BDay.get(Calendar.YEAR);
Log.v("checkFutureLeapYear",Integer.toString(CYear));
; if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
d=d;
}
else {
int date1=Integer.parseInt(d);
date1=(date1-1);
d=Integer.toString(date1);
Log.v("Date 29 subtracted to ",(d));
}
}
startDate=Integer.toString(CYear)+"/"+m+"/"+d;
sdf=new SimpleDateFormat("yyyy/MM/dd");
date=null;
try{
date=sdf.parse(startDate);
}
catch (Exception e) {
e.printStackTrace();
}
BDay.setTime(date);
Log.v("dfdfgdffgfgb",Integer.toString(BDay.get(Calendar.YEAR)));
}
String dayOfTheWeek;
Log.v("Birth year",Integer.toString(BDay.get(Calendar.YEAR)));
Log.v("Birth month",Integer.toString(BDay.get(Calendar.MONTH)));
Log.v("Birth date",Integer.toString(BDay.get(Calendar.DAY_OF_MONTH)));
SimpleDateFormat mFormat = new SimpleDateFormat("EEEE", Locale.US);
dayOfTheWeek = mFormat.format(BDay.getTime());
return dayOfTheWeek;

Related

How to get the number of days in a week given a string date

I have A string which is
String dateOfOrder = "01/06/2019";
I would like to get the number of days in Week 1 as June first week only have 1 day.
May i know how do i approach on receviing number of days in Week X ?
Like In June 2019
Week 1 : Have 1 day Week 2 - 5 : have 7 days Week 6 : Have 1 day
EDIT
I'm thinking of this approach of getting number of days in a week whereby I have a couple of String arrayList. For example on my given date above, if Week 1 Have Saturday. Week 1 Array List will add saturday in it and .size().
If Week 2 have Sunday to Saturday, it will add all the dates in the Week 2 Array List and .size() to get the number of days in the ArrayList.
Lastly, The last week of June which is Week 6 will have Sunday only and it will add into Week 6 ArrayList and have value of Sunday only and .size() to get 1.
I'm wondering if its the best approach and I'm not sure if i can get the correct days in the week.
Parse the string as date using SimpleDateFormatter. Your parsing pattern could be dd/MM/YYYY.
DateFormat df = new SimpleDateFormat("dd/MM/YYYY");
Date date = df.parse(dateOfOrder);
Once you have the date, get day of week using Calendar.
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
Calculate number of days in the given week (and month).
int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int currentMonth = c.get(Calendar.MONTH);
int prevWeekMonth = c.add(Calendar.DAY_OF_MONTH, -7).get(Calendar.MONTH);
c.setTime(yourDate);
int nextWeekMonth = c.add(Calendar.DAY_OF_MONTH, 7).get(Calendar.MONTH);
c.setTime(yourDate);
if (prevWeekMonth != currentMonth) {
// first or second week
if (dayOfMonth > dayOfWeek) {
// second week
numOfDaysInWeek = 7;
} else {
// first week
int firstDay = c.set(Calendar.DAY_OF_MONTH, 1).get(Calendar.DAY_OF_WEEK);
numOfDaysInWeek = 7 - firstDay;
}
} else if (nextWeekMonth != currentMonth) {
// last or second last week
if (dayOfMonth - dayOfWeek + 7 >= daysInMonth) {
// last week
numOfDaysInWeek = c.set(Calendar.DAY_OF_MONTH, daysInMonth).get(Calendar.DAY_OF_WEEK);
} else {
// second last week
numOfDaysInWeek = 7;
}
} else {
// middle weeks
numOfDaysInWeek = 7;
}
Note: the conditions are a bit rough and you might need to add 1 depending on whether dayOfWeek, dayOfMonth have 0 or 1 index.

How to compare time ranges?

Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog
start time:06:00
end time:23:00
selected time from time picker dialog:12:23
above timing not suitable for below code can some one help me please
String pattern = "hh:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {
}
else {
Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
}
You can use code below .
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
// Do your stuff
} else {
// Wrong time
}
} catch (Exception e) {
e.printStackTrace();
}
h represents Hour in am/pm (1-12)
H represents Hour in day (0-23)
Your date is in 24 hour formate so you should use H instead of h.
You should use compareTo().
CompareTo method must return negative number if current object is less
than other object, positive number if current object is greater than
other object and zero if both objects are equal to each other.
Code Reference
if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
Log.d("RESULT","date2 older than date1");
}
NOTE
Make sure your TIME format is perfect.

how can i repeat my date format showing in listview as today,yesterday,tue,mon,sun,...wed,

how can i display my listview with the following date formats like if its today date show only time , and yesterday ,and tue,mon,sun,sat,fri,thu,wed and agian started with time , ysterday, tue......etc ?
i tried with this code but i'm not getting
if(Constant.hours-Constant.hours1 <= 23){
holder.txtTime.setText(newDateString);
}else if(Constant.hours-Constant.hours1 >= 23 && Constant.hours-Constant.hours1 <= 47){
holder.txtTime.setText("Yesterday");
}else if(Constant.days >= 2 && Constant.days<=2){
holder.txtTime.setText(Constant.strLong+" days ago");
}
Try this one...
//suppose your date time format is "12-08-2017" of variable newDateString then date format will be like SimpleDateFormat formatter = SimpleDateFormat .forPattern("dd-MM-yyyy");//
String newDateString="08/02/2017 18:41:11";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
//SimpleDateFormat formatter = new SimpleDateFormat("your farmat here");
Date yourDate= null;
Date current= null;
Calendar cal = Calendar.getInstance();
try {
yourDate= formatter .parse(newDateString);//newDateString is your variable
current= formatter .parse(formatter.format(cal.getTime()));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int daysDiff= (int) ((yourDate.getTime() - current.getTime())/ (1000 * 60 * 60 * 24));
if(daysDiff< 1){
holder.txtTime.setText(newDateString);
}else if(daysDiff== 1){
holder.txtTime.setText("Yesterday");
}else if(daysDiff> 1){
holder.txtTime.setText(daysDiff+" days ago");
}
}else if(daysDiff<0){
holder.txtTime.setText(daysDiff+" days before");
}

Best way to format a date relative to now on Android

I am creating a feature in an Android app to get an arbitrary date (past, present or future) and find the difference relative to now.
Both my now and due variables are longs, and this is my code:
long now = System.currentTimeMillis();
long due = now + 864000;
Log.d("Time in 1 day", DateUtils.getRelativeTimeSpanString(due,now, DateUtils.DAY_IN_MILLIS));
I want the output to be something like yesterday, today, in 4 days or 19/12/2012. However, the current output returns in 0 days...
I don't want the time to appear on these date strings.
What am I doing wrong and is the best method for formatting dates on Android?
What I have in mind is changing:
DateUtils.getRelativeTimeSpanString(due, now, 0L, DateUtils.FORMAT_ABBREV_ALL);
Since the documentation says it returns the time relative to now.
If that fails use some of the brilliant libraries:
Joda Time
PrettyTime
TimeAgo
Finally I have implemented what you wanted..!
First you need to download Joda Time from here
Extract it to any folder and put joda-time-2.2.jar into androidProject/libs folder.
MainActivity
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.MutableDateTime;
import org.joda.time.Weeks;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity
{
private int day ;
private int month ;
private int year ;
private int hour ;
private int minute ;
private long selectedTimeInMillis;
private long currentTimeInMillis;
private String strDay ="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
year = 2013;
month = 8;
day = 10;
hour = 15;
minute = 28;
DateTime selectedTime = new DateTime(year,month,day,hour,minute);
selectedTimeInMillis = selectedTime.getMillis();
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(selectedTimeInMillis); //Set to Epoch time
DateTime now = new DateTime();
currentTimeInMillis = now.getMillis();
int days = Days.daysBetween(epoch, now).getDays();
int weeks = Weeks.weeksBetween(epoch, now).getWeeks();
int months = Months.monthsBetween(epoch, now).getMonths();
Log.v("days since epoch: ",""+days);
Log.v("weeks since epoch: ",""+weeks);
Log.v("months since epoch: ",""+months);
if(selectedTimeInMillis < currentTimeInMillis) //Past
{
long yesterdayTimeInMillis = currentTimeInMillis - 86400000;
DateTime today = new DateTime(currentTimeInMillis);
int year = today.getDayOfYear();
int intToday = today.getDayOfMonth();
DateTime yesterday = new DateTime(yesterdayTimeInMillis);
int intYesterday = yesterday.getDayOfMonth();
DateTime selectedDay = new DateTime(selectedTimeInMillis);
int intselectedDay = selectedDay.getDayOfMonth();
int intselectedYear = selectedDay.getDayOfYear();
if(intToday == intselectedDay & year == intselectedYear)
{
strDay = "today";
}
else if(intYesterday == intselectedDay)
{
strDay = "yesterday";
}
else
{
strDay = "before "+ days +" days from today";
}
}
else if(selectedTimeInMillis > currentTimeInMillis) //Future
{
long tomorrowTimeInMillis = currentTimeInMillis + 86400000;
DateTime tomorrow = new DateTime(tomorrowTimeInMillis);
int intTomorrow = tomorrow.getDayOfMonth();
DateTime today = new DateTime(selectedTimeInMillis);
int intToday = today.getDayOfMonth();
if(intToday == intTomorrow)
{
strDay = "tomorrow";
}
else
{
days = -days;
strDay = "after "+ days +" days from today";
}
}
Log.v("strDay: ",""+strDay);
}
}
You just need to change the value of day and you will get the desire output.
Currently I have given date 10 as input so output will be today.
I have set date/day = 10 , month = 8 , year = 2013 , hour = 15 , min = 28
For past dates:
input day 9 output yesterday
input day 3 output before 7 days from today
input year 2012 and day 10 output before 365 days from today
For future dates:
input day 11 output tomorrow
input day 27 output after 17 days from today
input day 23 and year 2016 output after 1109 days from today
Why not just check for yesterday and tomorrow to avoid the in 0 days/0 days ago bug and leave DateUtils.getRelativeTimeSpanString handle the remaining cases?
String relative = null;
if(now < due && (due-now)<864000){
relative = "tomorrow";
}else if(now > due && (now-due)<864000){
relative = "yesterday";
}else{
relative = DateUtils.getRelativeTimeSpanString(due, now, DateUtils.DAY_IN_MILLIS); // e.g. "in 4 days"
}
Log.d("result", relative);
Edit: You may also add today with a simple check as well.
Best way to format a date relative to now on Android
I suggest you to use JodaTime
It's lightweight handy library and i think actually the best tool for working with Date instances.
And you can start here.
build.gradle
compile 'joda-time:joda-time:2.9.9'
Utils.java
private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, yyyy");
private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(" 'at' h:mm aa");
public static String getRelativeDateTimeString(Calendar startDateCalendar) {
if (startDateCalendar == null) return null;
DateTime startDate = new DateTime(startDateCalendar.getTimeInMillis());
DateTime today = new DateTime();
int days = Days.daysBetween(today.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays();
String date;
switch (days) {
case -1: date = "Yesterday"; break;
case 0: date = "Today"; break;
case 1: date = "Tomorrow"; break;
default: date = DATE_FORMAT.format(startDateCalendar.getTime()); break;
}
String time = TIME_FORMAT.format(startDateCalendar.getTime());
return date + time;
}
Output
Yesterday at 9:52 AM
Today at 9:52 AM
Tomorrow at 9:52 AM
Sep 05, 2017 at 9:52 AM
The actual reason is the number 864000 is in miliseconds, which corresponds to 14 minutes. 14 minutes is so small compared to DAY_IN_MILLIS (a day). There for you get "in 0 days".
If you want it to produce "in 14 mins", just change DAY_IN_MILLIS to MIN_IN_MILLIS.
I came here for an alternative but I can't find perfect rather than my code.
So I shared here any improvements are welcome.
public String getCreatedAtRelative() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("IST"));
CharSequence relative = null;
try {
relative = DateUtils.getRelativeTimeSpanString(df.parse(createdAt).getTime(), new Date().getTime(),
0L, DateUtils.FORMAT_ABBREV_ALL);
} catch (ParseException e) {
Log.e("Parse Exception adapter", "created at", e);
} catch (NullPointerException e) {
e.printStackTrace();
}
if (null == relative) {
return createdAt;
} else {
return relative.toString().replace(".", " ");
}
}
So your computation is based on milliseconds unit, then you format the result with SimpleDateFormat.
For this, you can easily use SimpleDateFormat formatter like this :
Date date = new Date(milliseconds);
SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM yyyy");
String strDate = formatter.format(date);
So your computation should be based on milliseconds unit, then you format the result with SimpleDateFormat.
The pattern ("EEEE dd MMMM yyyy") allows you to get a date format like Monday, 04 February 2013.
You can change the pattern as you like : "EEEE dd/MM/yy", ...
for Android you can use most simple way with Joda-Time-Android library:
Date yourTime = new Date();
DateTime dateTime = new DateTime(yourTime); //or simple DateTime.now()
final String result = DateUtils.getRelativeTimeSpanString(getContext(), dateTime);
long now = System.currentTimeMillis();
DateUtils.getRelativeDateTimeString(mContext, now), DateUtils.SECOND_IN_MILLIS, DateUtils.DAY_IN_MILLIS, 0)
a link!

setting particular date to Date object

I've been trying this from a long time.
I'm having today's date and I want to compare it with specific date.
But when I set particular date like this, it gives me wrong output:
Calendar cal;
SimpleDateFormat dateformatter;
String currentdate;
cal = Calendar.getInstance();
dateformatter = new SimpleDateFormat("yyyy-MM-dd");
//Getting today's date
currentdate = dateformatter.format(cal.getTime());
Log.i(Class_Tag, "current = " + currentdate);
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
Log.i(Class_Tag, "end = " + dateformatter.format(end));
long diff = end.getDate() - start.getDate();
Log.i(Class_Tag, "diff : " + diff);
long diff1 = end.getMonth() - start.getMonth();
Log.i(Class_Tag, "diff mnth : " + diff1);
long diff2 = end.getYear() - start.getYear();
Log.i(Class_Tag, "diff yr : " + diff2);
if (start.compareTo(end) == 0) {
Log.i(Class_Tag, "EQUAL");
} else if (start.compareTo(end) < 0) {
Log.i(Class_Tag, "end b4 start, delete");
} else {
Log.i(Class_Tag, "start b4 end, do nothing");
OUTPUT:
current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct
I've tried several solutions, but no gains.
My only objective is to get whether that particular date has passed today's date or not.
Any help appreciated.
Edit
in the following code snippet,
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
If I set cal.set(2012, 06, 20); to cal.set(2012, 05, 20);, the month diff. comes out to 0.
This implies that month in particular date is getting incremented by '1', but WHY?
Try this;
Calendar cal = Calendar.getInstance();
long dateNowMillis = cal.getTimeInMillis();
cal.set(2013, 1, 23);
long specDate = cal.getTimeInMillis();
if(dateNowMillis > specDate)
{
System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
System.out.println("Now");
}
else
{
System.out.println("Not passed");
}
FYI,
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
You can check read more about Date here and more about SimpleDateFormat.
Update:
One more thing about getMonth() => Its deprecated, instead Calendar.get(Calendar.MONTH), check here.

Categories

Resources