Date Picker with max and minimum date in onDateChanged() in Android 1.5? - android-datepicker

I am working on DatePicker in android 1.5. I am trying to set Maximum and minimum date.Minimum date should be the current date and maximum date should be the date which I will supply from string as maxYear, maxMonth, maxDay.(Suppose Todays date=30/12/2011, but it selects 29/12/2011)
Everything working fine with minimum date.As it shows current date only.But on selection using minus button on picker, it selects a date less than today's date.
While in case of maximum date selection it selects day, month and year more than the maximum date.
How to restrict user not to select less than minimum date and maximum date. What extra condition I have to put to make it perfect?
enter code here
///Whole code same
mport java.sql.Date;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerActivity extends Activity implements Button.OnClickListener {
public String dateOutput=null;
final Calendar c = Calendar.getInstance();
int minYear1 = c.get(Calendar.YEAR);
int minMonth1 = c.get(Calendar.MONTH);
int minDay1 = c.get(Calendar.DAY_OF_MONTH);
int maxYear = 2011;//
int maxMonth = 12;
int maxDay = 29;
int minYear = minYear1;
int minMonth = minMonth1;
int minDay = minDay1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatePicker DateDP = (DatePicker) findViewById (R.id.ad_date_picker);
DateDP.init(minYear1, minMonth1, minDay1, new OnDateChangedListener()
{
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < minYear)
view.updateDate(minYear, minMonth, minDay);
if (monthOfYear < minMonth && year == minYear )
view.updateDate(minYear, minMonth, minDay );
if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
view.updateDate(minYear, minMonth, minDay);
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
dateOutput = String.format("Date Selected: %02d/%02d/%04d",
dayOfMonth, monthOfYear+1, year);
// Log.d("Debug", dateOutput);
Toast.makeText(DatePickerActivity.this,dateOutput, Toast.LENGTH_SHORT).show();
}}); // DateDP.init()
}
}

This way, i solved my problem
DateDP.init(minYear, minMonth, minDay, new OnDateChangedListener()
{
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year > maxYear ||monthOfYear > maxMonth && year == maxYear||
dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth){
// Toast.makeText(DatePickerActivity.this,"max year", Toast.LENGTH_SHORT).show();
view.updateDate(maxYear, maxMonth, maxDay);
dateOutput = String.format("%04d-%02d-%02d",
maxYear, maxMonth+1, maxDay);
//Toast.makeText(DatePickerActivity.this,"maxYear "+dateOutput, Toast.LENGTH_SHORT).show();
}else if(year < minYear ||monthOfYear < minMonth && year == minYear||
dayOfMonth < minDay && year == minYear && monthOfYear == minMonth){
//Toast.makeText(DatePickerActivity.this,"min year", Toast.LENGTH_SHORT).show();
view.updateDate(minYear, minMonth, minDay );
dateOutput = String.format("%04d-%02d-%02d",
minYear, minMonth+1, minDay);
//Toast.makeText(ManageShowing.this,dateOutput, Toast.LENGTH_SHORT).show();
}else{
//Toast.makeText(ManageShowing.this,"else", Toast.LENGTH_SHORT).show();
dateOutput = String.format("%04d-%02d-%02d",
year, monthOfYear+1, dayOfMonth);
// Toast.makeText(ManageShowing.this,dateOutput, Toast.LENGTH_SHORT).show();
}
mDateDisplay.setText(dateOutput);
}}); // DateDP.init()

Related

How to calculate date in kotlin with the given format?

How to see if a user can be unbanned or not between 2 dates?
Hi, I have a given variable which is the date the user was unbanned as end_banned in the format HH:mm:ss dd/MM/YYYY.
val end_banned: String= "15:05:00 12/01/2022"
I want to calculate if at the current time they can be unbanned or not. I have tried with SimpleDateFormat, Calendar, Date... but still haven't found a solution.
I've tried separating each element of seconds, minutes, days... and comparing them with if...else like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var _hours = cal.get(Calendar.HOUR)
var _minutes = cal.get(Calendar.MINUTE)
var _seconds = cal.get(Calendar.SECOND)
var _day = cal.get(Calendar.DAY_OF_MONTH)
var _month = cal.get(Calendar.MONTH) + 1
var _year = cal.get(Calendar.YEAR)
var hours = end_banned.toString().substring(0, 2).toInt()
var minutes = end_banned.toString().substring(3, 5).toInt()
var seconds = end_banned.toString().substring(6, 8).toInt()
var day = end_banned.toString().substring(9, 11).toInt()
var month = end_banned.toString().substring(12, 14).toInt()
var year = end_banned.toString().substring(15).toInt()
if (_year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes && _seconds >= seconds
|| _year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes
|| _year >= year && _month >= month && _day >= day && _hours >= hours
|| _year >= year && _month >= month && _day >= day
|| _year >= year && _month >= month
|| _year >= year) {
println("True")
} else {
println("False")
}
But it is only true for the first 3 conditions when there are hours, minutes and seconds.
I tried with SimpleDateFormat and Date like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var hours = cal.get(Calendar.HOUR)
var minutes = cal.get(Calendar.MINUTE)
var seconds = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var sdf_unbanned = sdf.parse(end_banned)
var sdf_now = sdf.parse("${hours}:${minutes}:${seconds} ${day}/${month}/${year}")
if (sdf_now.time - sdf_unbanned.time <= 0) {
println(true)
} else {
println(false)
}
But this condition always gives an incorrect number if I adjust the now and unbanned variables a few minutes apart (This makes it easier to spot)
I did not fully understand your question Sir, But I assume you want to compare unbanned_date to the current date (now time) if they are the same(we reached the unban date) then it should unban whatever you are unbanning, If so the implementation requires less code to achieve that ,Like this :
val sdf = SimpleDateFormat("dd/MM/yyyy")
val strDate: Date = sdf.parse(end_banned)
if (System.currentTimeMillis() > strDate.getTime()) {
urbanUser = true // or what ever your logic is
}
Shame, I got confused between cal.get(Calendar.HOUR) and cal.get(Calendar.HOUR_OF_DAY)
Because cal.get(Calendar.HOUR) returns only 12h format
And cal.get(Calendar.HOUR_OF_DAY) will return 24h format
I found a workaround and here is the code that I fixed and tested:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var hour = cal.get(Calendar.HOUR_OF_DAY)
var minute = cal.get(Calendar.MINUTE)
var second = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var now: Date? = sdf.parse("${hour}:${minute}:${second} ${day}/${month}/${year}")
var end: Date? = sdf.parse(end_banned)
return now?.time!! > end?.time!!
Thanks for the help.

Age Calculator Difference in Kotlin [duplicate]

This question already has answers here:
How to create method for age calculation method in android
(7 answers)
Closed 4 months ago.
I have DatePicker Dialog, When I select date at that time I want to calculate age it's working but when I select date of current year at that time it showing the -1 age instead of 0 then how can solve this? Please help me to solve it.
My code is below:
public int getAge(int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);// current day
cal.set(year, month, day);// here ur date
noofyears = (int) (y - cal.get(Calendar.YEAR));
LOGD("Age......", String.valueOf(noofyears));
if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0) {
ageCount = noofyears;
} else {
ageCount = 0;
}
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;
}
java.time
For the sake of completeness and being up-to-date concerning packages, here is the way using java.time (Java 8+).
Java
public int getAge(int year, int month, int dayOfMonth) {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).getYears();
}
Kotlin
fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).years
}
Both snippets need the following imports from java.time:
import java.time.LocalDate;
import java.time.Period
It's not recommended to use java.util.Date and java.util.Calendar anymore except from situations where you have to involve considerably large amounts of legacy code.
See also Oracle Tutorial.
For projects supporting Java 6 or 7, this functionality is available via the ThreeTenBP,
while there is special version, the ThreeTenABP for API levels below 26 in Android.
UPDATE
There's API Desugaring now in Android, which makes (a subset of) java.time directly available (no backport library needed anymore) to API levels below 26 (not really down to version 1, but will do for most of the API levels that should be supported nowadays).
private int getAge(String dobString){
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(dobString);
} catch (ParseException e) {
e.printStackTrace();
}
if(date == null) return 0;
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.setTime(date);
int year = dob.get(Calendar.YEAR);
int month = dob.get(Calendar.MONTH);
int day = dob.get(Calendar.DAY_OF_MONTH);
dob.set(year, month+1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
return age;
}
Here is a Kotlin extension of the Date class returning the age corresponding to a Date object
val Date.age: Int
get() {
val calendar = Calendar.getInstance()
calendar.time = Date(time - Date().time)
return 1970 - (calendar.get(Calendar.YEAR) + 1)
}
It is compatible for all Android versions. If you wonder what '1970' is, that's the Unix Epoch. The timestamp is 0 on January 1, 1970.
private boolean getAge(int year, int month, int day) {
try {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int monthToday = today.get(Calendar.MONTH) + 1;
int monthDOB = dob.get(Calendar.MONTH)+1;
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (age > 18) {
return true;
} else if (age == 18) {
if (monthDOB > monthToday) {
return true;
} else if (monthDOB == monthToday) {
int todayDate = today.get(Calendar.DAY_OF_MONTH);
int dobDate = dob.get(Calendar.DAY_OF_MONTH);
if (dobDate <= todayDate) { // should be less then
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static int getPerfectAgeInYears(int year, int month, int date) {
Calendar dobCalendar = Calendar.getInstance();
dobCalendar.set(Calendar.YEAR, year);
dobCalendar.set(Calendar.MONTH, month);
dobCalendar.set(Calendar.DATE, date);
int ageInteger = 0;
Calendar today = Calendar.getInstance();
ageInteger = today.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) == dobCalendar.get(Calendar.MONTH)) {
if (today.get(Calendar.DAY_OF_MONTH) < dobCalendar.get(Calendar.DAY_OF_MONTH)) {
ageInteger = ageInteger - 1;
}
} else if (today.get(Calendar.MONTH) < dobCalendar.get(Calendar.MONTH)) {
ageInteger = ageInteger - 1;
}
return ageInteger;
}
Consider Today's Date - 30th August 2020
If Birthdate - 29th July 1993, the output - 27
If Birthdate - 29th August 1993, the output - 27
If Birthdate - 30th August 1993, the output - 27
If Birthdate - 31st August 1993, the output - 26
If Birthdate - 31st September 1993, the output - 26
Now for kotlin Language:
import java.util.Calendar
fun main(args: Array<String>) {
print(getAge(yyyy,mm,dd))
}
fun getAge(year: Int, month: Int, day: Int): String {
val dob = Calendar.getInstance()
val today = Calendar.getInstance()
dob.set(year, month, day)
var age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR)
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
age--
}
val ageInt = age + 1
return ageInt.toString()
}
private void calculateAge() {
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
age.calculateMonths();
age.calTotalWeeks();
age.calTotalHours();
age.calTotalMins();
age.calTotalSecs();
age.calTotalMilsecs();
// Toast.makeText(getContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
result.setText("AGE (DD/MM/YY) :" + age.getResult());
}
after that create one class
public class AgeCalculation {
private int startYear;
private int startMonth;
private int startDay;
private int endYear;
private int endMonth;
private int endDay;
private int resYear;
private int resMonth;
private int resDay;
private Calendar start;
private Calendar end;
public String getCurrentDate()
{
end=Calendar.getInstance();
endYear=end.get(Calendar.YEAR);
endMonth=end.get(Calendar.MONTH);
endMonth++;
endDay=end.get(Calendar.DAY_OF_MONTH);
return endDay+":"+endMonth+":"+endYear;
}
public void setDateOfBirth(int sYear, int sMonth, int sDay)
{
startYear=sYear;
startMonth=sMonth;
startDay=sDay;
}
public void calcualteYear()
{
resYear=endYear-startYear/(365);
}
public void calcualteMonth()
{
if(endMonth>=startMonth)
{
resMonth= endMonth-startMonth;
}
else
{
resMonth=endMonth-startMonth;
resMonth=12+resMonth;
resYear--;
}
}
public void calcualteDay()
{
if(endDay>=startDay)
{
resDay= endDay-startDay;
}
else
{
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
{
resMonth=11;
resYear--;
}
else
{
resMonth--;
}
}
}
public String getResult()
{
return resDay+":"+resMonth+":"+resYear;
}
public String getAge(int year, int month, int day) {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month-1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
static int calculateAge(int birthdayDay, int birthdayMonth, int birthdayYear)
{
DateTime date = DateTime(birthdayYear, birthdayMonth, birthdayDay).toLocal();
DateTime now = DateTime.now().toLocal();
return now.difference(date).inDays ~/ 365.2425;
}
public int getAge(int year, int month, int day) {
final Calendar birthDay = Calendar.getInstance();
birthDay.set(year, month, day);
final Calendar current = Calendar.getInstance();
if (current.getTimeInMillis() < birthDay.getTimeInMillis())
throw new IllegalArgumentException("age < 0");
int age = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.MONTH) > current.get(Calendar.MONTH) ||
(birthDay.get(Calendar.MONTH) == current.get(Calendar.MONTH) &&
birthDay.get(Calendar.DATE) > current.get(Calendar.DATE)))
age--;
return age;
}
This is how I implement in my source code, I tested. Hope that it is useful :
public static int getAge(String dateTime, String currentFormat) {
SimpleDateFormat dateFormat = new SimpleDateFormat(currentFormat);
try {
Date date = dateFormat.parse(dateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
Date currentDate = new Date();
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentDate);
int currentYear = currentCalendar.get(Calendar.YEAR);
int currentMonth = currentCalendar.get(Calendar.MONTH);
int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);
int deltaYear = currentYear - year;
int deltaMonth = currentMonth - month;
int deltaDay = currentDay - day;
if (deltaYear > 0) {
if (deltaMonth < 0) {
deltaYear --;
} else if (deltaDay < 0){
deltaYear --;
}
return deltaYear;
}
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return 0;
}
String getAgeInOther(int year, int month, int day) {
Calendar today = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.set(year, month, day);
Calendar temp = Calendar.getInstance();
temp.set(year, month, day);
int totalDays = 0;
int intMonth=0,intDays=0;
for (int iYear = birth.get(Calendar.YEAR); iYear <= today.get(Calendar.YEAR); iYear++) {
if (iYear == today.get(Calendar.YEAR) && iYear == birth.get(Calendar.YEAR)) {
for (int iMonth = birth.get(Calendar.MONTH); iMonth <= today.get(Calendar.MONTH); iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH)) && (iMonth == birth.get(Calendar.MONTH))) {
totalDays += today.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);
} else if ((iMonth != today.get(Calendar.MONTH)) && (iMonth != birth.get(Calendar.MONTH))) {
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
}else if ((iMonth == birth.get(Calendar.MONTH))) {
totalDays +=( birth.getActualMaximum(Calendar.DAY_OF_MONTH)- birth.get(Calendar.DAY_OF_MONTH));
} else if ((iMonth == today.get(Calendar.MONTH))){
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
{
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
}else {
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
}
}
}
} else if ((iYear != today.get(Calendar.YEAR)) && (iYear != birth.get(Calendar.YEAR))) {
for (int iMonth = 0; iMonth < 12; iMonth++) {
temp.set(iYear, iMonth, 1);
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
}
} else if (((iYear) == birth.get(Calendar.YEAR))) {
for (int iMonth = birth.get(Calendar.MONTH); iMonth < 12; iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == birth.get(Calendar.MONTH))) {
totalDays += (birth.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH));
} else {
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
} else if (iYear == today.get(Calendar.YEAR)) {
for (int iMonth = 0; iMonth <= today.get(Calendar.MONTH); iMonth++) {
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH))) {
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
{
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
}else {
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
}
} else {
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
}
}
int ageYear=intMonth/12;
int ageMonth=intMonth%12;
int ageDays=intDays;
//TODO if you want age in YEAR:MONTH:DAY REMOVE COMMENTS
//TODO return ageYear+":"+ageMonth+":"+ageDays;
return ""+totalDays;//todo TOTAL AGE IN DAYS
}
public static String calculateAge(String strDate) {
int years = 0;
int months = 0;
int days = 0;
try {
long timeInMillis = Long.parseLong(strDate);
Date birthDate = new Date(timeInMillis);
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate.getTime());
//create calendar object for current day
long currentTime = System.currentTimeMillis();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(currentTime);
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0) {
years--;
months = 12 - birthMonth + currMonth;
if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
months--;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
years--;
months = 11;
}
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
} else {
days = 0;
if (months == 12) {
years++;
months = 0;
}
}
//adarsh
if (currMonth > birthMonth) {
if (birthDay.get(Calendar.DATE) > now.get(Calendar.DATE)) {
months = months - 1;
}
}//---------------------------------
} catch (Exception e) {
e.printStackTrace();
}
//Create new Age object
return years + " Y " + months + " M " + days + " days";
}
Here is my solution in Kotlin:
import java.time.LocalDateTime
fun getAge(birthYear: Int, birthMonth: Int, birthDay: Int): Int {
var age: Int = LocalDateTime.now().year - birthYear
if (birthMonth > LocalDateTime.now().monthValue || birthMonth == LocalDateTime.now().monthValue && birthDay > LocalDateTime.now().dayOfMonth) { age-- }
if (age < 0) { age = 0 }
return age
}
int age =0;
age = yearLatest - yearBirth;
if (monthAge > currentMonth) {
if (age != 0) {
age = age - 1;
}
} else if(monthAge == currentMonth){
if (dayAge > currentDay) {
if (age != 0) {
age = age - 1;
}
}
}
return age;
If we want to directly check if age is below or above X age then we can use LocalDate type, work for all the Android API levels.
LocalDate.now().minusYears(18).isBefore(value) //value is your localDate
This is the shortest I could get it to.
static int calculateAge(Calendar birthDay){
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR)) {
age--;
}
return age;
}
New Language Dart using DateTime
static int getPerfectAgeInYears(DateTime dob,DateTime today) {
dob = DateTime(dob.year,dob.month,dob.day);
int ageInteger = 0;
today = DateTime(today.year,today.month,today.day);
ageInteger = today.year-dob.year;
if (today.month == dob.month) {
if (today.day < dob.day) {
ageInteger = ageInteger - 1;
}
} else if (today.month < dob.month) {
ageInteger = ageInteger - 1;
}
return ageInteger;}
Call as print(getPerfectAgeInYears(DateTime(2000,6,4),DateTime.now()));
Consider Today's Date - 30th August 2020
If Birthdate - 29th July 1993, the output - 27
If Birthdate - 29th August 1993, the output - 27
If Birthdate - 30th August 1993, the output - 27
If Birthdate - 31st August 1993, the output - 26
If Birthdate - 31st September 1993, the output - 26

asp.net mvc , raw sql : Display data in Views generated using aggregate function

I am using ASP.NET MVC, EF 6 and SQL Server 2008.
I want to generate a view which would show sum of all the sales in each day for a particular month in a particular year.
I found LINQ query very complicated in such type of job, So I used a raw SQL query. I wrote query and tested in SQL server and it worked fine.
select
YEAR(Date) as Year,
MONTH(Date) as month,
DAY(Date) as date,
SUM(GrandTotal) as Total
from
Sales
where
Year(Date) = 2014
and MONTH(Date) = 12
group by
DAY(Date), YEAR(Date), MONTH(date)
Result
Well currently I don't have much data. But it looks like I got what I wanted from a query.
I wrote a controller for this purpose and now I have no idea how to display this data in View.
public ActionResult MonthlySalesByDate()
{
DateTime today = DateTime.Now.Date;
int _year = today.Year;
int _month = today.Month;
//raw sql query
string query = "select SUM(GrandTotal) as Total, DAY(Date) as date, MONTH(Date) as month, YEAR(Date) as Year from Sales where Year(Date) = " + _year + " and MONTH(Date) =" + _month + " Group by DAY(Date), YEAR(Date), MONTH(date)";
//executing raw sql query
var _model = db.Stocks.SqlQuery(query).ToList();
return View(_model);
}
Please help me out with this. If there is better way of doing this or if I am making mistakes, please let me know.
Start by creating view models to represent what you want to display in the view
public class DayTotalVM
{
public int Day { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Total { get; set; }
}
public class SalesVM
{
[DisplayFormat(DataFormatString = "{0:MMMM yyyy}")]
public DateTime Date { get; set; }
public List<DayTotalVM> Days { get; set; }
}
The sql query you have can be generated in linq and projected into your view models using
int year = 2014;
int month = 12;
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month)
.GroupBy(x => x.Date).Select(g => new DayTotalVM
{
Day = g.Key.Day,
Total = g.Sum(x => x.Total)
})
However this will only give you the 2 items as per you above image, but from the comments you want to display all days in the month, so you can add
int daysInMonth = DateTime.DaysInMonth(year, month);
List<DayTotalVM> days = new List<DayTotalVM>();
for(int i = 1; i < daysInMonth + 1; i++)
{
DayTotalVM item = new DayTotalVM () { Day = i };
DayTotalVM ex = query.Where(x => x.Day == i).FirstOrDefault();
if (ex != null)
{
item.Total = ex.Total;
}
days.Add(item);
}
and finally initialize and return your view model
SalesVM model = new SalesVM();
{
Date = new DateTime(year, month, 1),
Days = days
}
return View(model);
And then the view would be
#model SalesVM
#Html.DisplayFor(m => m.Date);
<table>
#for(int i = 0; i < Model.Days.Count; i++)
{
<tr>
<td>#Html.DisplayFor(m => m.Days[i].Day)</td>
<td>#Html.DisplayFor(m => m.Days[i].Total)</td>
</tr>
}
</table>
Edit
The for loop could be replace by using a GroupJoin()
public ActionResult MonthlySalesByDate(int year, int month)
{
int daysInMonth = DateTime.DaysInMonth(year, month);
var days = Enumerable.Range(1, daysInMonth);
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month).Select(g => new
{
Day = g.Date.Day,
Total = g.Total
});
var model = new SalesVM
{
Date = new DateTime(year, month, 1),
Days = days.GroupJoin(query, d => d, q => q.Day, (d, q) => new DayTotalVM
{
Day = d,
Total = q.Sum(x => x.Total)
}).ToList()
};
return View(model);
}

How to select all the days of the week from a given day?

Given a date I want to get all the other days of that same week, where in the week starts and ends on Saturday and Friday.
Model
public TimeModel
{
public int ID
public DateTime Day
}
What I'm currently doing
public Contrller{
private db = new ModelContext();
public AddDates(DateTime Date)
{
List<Model> list = new List<Model>();
int n = 0;
while(Date.DayofWeek != DayofWeek.Sauturday)
Date = Date.AddDats(-1) // keep subracting the date until I reach Saturday
while(Date.DayofWeek != DayofWeek.Friday
{
list.Add(Find(Date));
//Simply put for each date not Friday
// I find the corresponding model (the one with the same date)
//and add it to the list
Date = Date.AddDays(1)
}
list.Add(Find(Date)); // To add the Friday date to list
}
Note: Not exactly my code, just a simplification of my problem.
To summarize my solution:
a) Subtract given date until Saturday
b) Find model which corresponds to Date
c) Repeat until I reach Friday
d) Add to list once more to include Friday
Is it possible to create a linq/sql statement to simpyly select the needed models (with regards to Date)?
You can find a sample implementation that gets the current week.
List<TimeModel> list = new List<TimeModel>();
int n = 0;
for (int i = 0; i < 200; i++)
list.Add(new TimeModel{ID = i, Day = DateTime.Now.AddDays(-i)});
var currentDay = new TimeModel() {ID = 0, Day = DateTime.Now};
var previousSaturday = currentDay.Day.AddDays(-(int)currentDay.Day.DayOfWeek - 1);
var nextFriday = previousSaturday.AddDays(6);
var currentWeek = list.Where(p => p.Day.DayOfYear >= previousSaturday.DayOfYear && p.Day.DayOfYear <= nextFriday.DayOfYear).OrderBy(p => p.Day.DayOfYear).ToList();

AlarmManager only firing when date is now

For some reason, my alarm only fires when the date is now , e.g. 12.10pm if it is 12.10pm. And all other dates set are not fired. I am using AlarmManager and a bit puzzled by it. Can anyone help
This is the method I set the alarm in a class
/**
* Set up alarm from user input
*/
public void setUpAlarm() {
// get the time reminder hour and minute from user's input time value
String[] timeVals = time.split(":");
int hourOfDay = Integer.parseInt(timeVals[0].trim());
int minOfDay = Integer.parseInt(timeVals[1].trim());
// get the Date from User date value
String[] dateVals = date.split("/");
int day = Integer.parseInt(dateVals[0].trim());
int month = Integer.parseInt(dateVals[1].trim());
int year = Integer.parseInt(dateVals[2].trim());
Calendar calendar = Calendar.getInstance();
// set calendar based on user input
if (month == 1) {
calendar.set(Calendar.MONTH, Calendar.JANUARY);
System.out.println("jan");
} else if (month == 2) {
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println("feb");
} else if (month == 3) {
calendar.set(Calendar.MONTH, Calendar.MARCH);
System.out.println("march");
} else if (month == 4) {
calendar.set(Calendar.MONTH, Calendar.APRIL);
System.out.println("april");
} else if (month == 5) {
calendar.set(Calendar.MONTH, Calendar.MAY);
System.out.println("may");
} else if (month == 6) {
calendar.set(Calendar.MONTH, Calendar.JUNE);
System.out.println("june");
} else if (month == 7) {
calendar.set(Calendar.MONTH, Calendar.JULY);
System.out.println("july");
} else if (month == 8) {
calendar.set(Calendar.MONTH, Calendar.AUGUST);
System.out.println("august");
} else if (month == 9) {
calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
System.out.println("september");
} else if (month == 10) {
calendar.set(Calendar.MONTH, Calendar.OCTOBER);
System.out.println("october");
} else if (month == 11) {
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
System.out.println("november");
} else if (month == 12) {
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
System.out.println("december");
}
// set year
calendar.set(Calendar.YEAR, year);
// set day
calendar.set(Calendar.DAY_OF_MONTH, day);
// set hour of day
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
// calendar set Minute of Day
calendar.set(Calendar.MINUTE, minOfDay);
// set AM or PM
if (hourOfDay < 12) {
calendar.set(Calendar.AM_PM, Calendar.AM);
} else {
calendar.set(Calendar.AM_PM, Calendar.PM);
}
// create intent for alarm
Intent myIntent = new Intent(confirmTaskForm.this,
MyAlarmReceiver.class);
// create pending intent
pendingIntent = PendingIntent.getBroadcast(confirmTaskForm.this, 0,
myIntent, 0);
// set-up alarm manager
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// send pendingIntent to alarmManager
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
}
and this then fires the broadcast receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
/**
* Feeder class sending data to MyAlarmService
* #author Aaron
*
*/
public class MyAlarmReceiver extends BroadcastReceiver{
int taskID ;
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
and then the notification
package com.example.prototype4.alarm;
import com.example.prototype4.MainActivity;
import com.example.prototype4.R;
import com.example.prototype4.Points.Achievments;
import com.example.prototype4.database.DatabaseHelper;
import com.example.prototype4.home.TaskListView;
import com.example.prototype4.task.Task;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.CursorIndexOutOfBoundsException;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
/**
* Main Alarm functionality for Alarm is performed here
*
* #author Aaron
*
*/
public class MyAlarmService extends Service {
NotificationManager mManager;
DatabaseHelper db;
int taskID;
Task currentTask;
String taskTitle;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
//instantiate database
db = new DatabaseHelper(this);
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings({ "static-access", "deprecation" })
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get current task
try{
currentTask = db.getLastTaskFromDatabase();
taskTitle = currentTask.getTaskTitle();
// update task with deadline = true
currentTask.setDeadline("true");
db.updateTask(currentTask);
mManager = (NotificationManager) this.getApplicationContext()
.getSystemService(
this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),
MainActivity.class);
Notification notification = new Notification(R.drawable.ic_app_logo,
"Task Deadline Has Passed!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "Task: ",
"Make sure you complete task : " + taskTitle,
pendingNotificationIntent);
mManager.notify(0, notification);
}catch(CursorIndexOutOfBoundsException e){
System.out.println("Task has already been completed before deadline fired");
}catch(NullPointerException e){
System.out.println("Task cannot be obtained after it has been completed");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}