I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:
If the current time is within
time1 and time2?
time1 will happen in the nearest
hour?
Upd.
I've implemented the following to convert time1 to Date format. But it uses depreciated methods:
Date clTime1 = new Date();
SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}
Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
Convert the two strings to Date
objects (which are also time objects)
Create a new Date object.
This will
contain the current time.
Use the
Date.before() and Date.after() methods to determine if
you are in the time interval.
EDIT: You should be able to use this directly (and no deprecated methods)
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//yada yada
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
This is what I used as simple function and it worked for me:
public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
boolean isBetween = false;
try {
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);
if (time1.before(d) && time2.after(d)) {
isBetween = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isBetween;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date EndTime = dateFormat.parse("10:00");
Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
if (CurrentTime.after(EndTime))
{
System.out.println("timeeee end ");
}
Don't forget to surrounded with a try catch block
if you want time between after 9PM to before 9Am you can use following condition..
if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
// do your stuffs
}
Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.
Here is the link to the API. Calendar
About the usage. First you need to call Calendar.getInstance() to create a calendar object.
Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.
For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.
// Code
package com.example.timedate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
Button bt;
int hour,min;
String AM_PM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
bt = (Button)findViewById(R.id.button1);
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
int ds = c.get(Calendar.AM_PM);
if(ds==0)
AM_PM="am";
else
AM_PM="pm";
Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am")) || (hour==12&&AM_PM.matches("am")))
{
Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}`
As of now, I am thinking about the following approach:
int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4));
Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;
So, I'll need to compare just integer values clTime and nowTime.
Try this if you have specific time Zone.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
Date timeseven = dateFormat.parse("7 AM");
Date timeTen = dateFormat.parse("10 AM");
Date timeOne = dateFormat.parse("1 PM");
Date timefour = dateFormat.parse("4 PM");
Date timefive = dateFormat.parse("10 PM");
//Get current time
// Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
//Sample time
Date CurrentTime = dateFormat.parse("9 PM");
if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
class TimeRange {
LocalTime from;
LocalTime to;
public TimeRange(LocalTime from, LocalTime to) {
this.from = from;
this.to = to;
}
public boolean isInRange(Date givenDate) {
LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
}
public static LocalDateTime getLocalDateTime(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
}
Related
I use Material design to implement Date Picker but I need to disabled the user select some specific dates how I can implement this ?
Below is my code:
button=findViewById(R.id.select_date);
Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
long today=MaterialDatePicker.todayInUtcMilliseconds();
CalendarConstraints.Builder cons=new CalendarConstraints.Builder();
cons.setValidator(DateValidatorPointForward.now());
MaterialDatePicker.Builder builder=MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Select booking date");
builder.setSelection(today);
builder.setCalendarConstraints(cons.build());
MaterialDatePicker materialDatePicker=builder.build();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Date Picker");
}});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
System.out.println(materialDatePicker.getHeaderText());
}
});
}
}
The values in this Calendar[] are explicitly disabled (not selectable). This option can be used together with setSelectableDays(Calendar[] days): in case there is a clash setDisabledDays(Calendar[] days) will take precedence over setSelectableDays(Calendar[] days)
String[] holidays = {"07-03-2018","05-03-2018","10-03-2018"};
java.util.Date date = null;
for (int i = 0;i < holidays.length; i++) {
try {
date = sdf.parse(holidays[i]);
} catch (ParseException e) {
e.printStackTrace();
}
calendar = dateToCalendar(date);
System.out.println(calendar.getTime());
List<Calendar> dates = new ArrayList<>();
dates.add(calendar);
Calendar[] disabledDays1 = dates.toArray(new Calendar[dates.size()]);
dpd.setDisabledDays(disabledDays1);
}
private Calendar dateToCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
I'm super-new in Java and Android Studio. I've started app with date functionality. I've created 3 buttons in app menu. One is button back, date, and button forward.
case 1. When you start the app, current date shows up on date button, when you click button back or forward that date on the middle button changes accordingly by one day.
case 2. When you click date button itself (for the first time) it pops out the date picker with the date from the button highlighted, you can change the date and it changes the date button accordingly from the picker.
case 3. But when I use buttons forward and back after the picker was out (once) date still changes on the button, but it does not highlights in the picker. It only highlights correctly first time around, it also highlights correctly when changing date via picker, but not via back and forward buttons.
What am I doing wrong (beside using deprecated methods? ;-)). Any input will be very appreciated.
//variables for date
int year_x,month_x,day_x;
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
MenuItem dynamicDate;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
dynamicDate = menu.findItem(R.id.action_date);
Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH) + 1;
day_x = cal.get(Calendar.DAY_OF_MONTH);
String currentDateString = (day_x<10?("0"+day_x):(day_x)) + "-" + (month_x<10?("0"+month_x):(month_x)) + "-" + year_x;
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
dynamicDate.setTitle(currentDateString);
return true;
}
public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year_xk, int month_xk, int day_xk) {
Calendar cal = Calendar.getInstance();
cal.set(year_xk, month_xk, day_xk);
Date dateAfterChange = cal.getTime();
String dateAfterChangeString = df.format(dateAfterChange);
dynamicDate.setTitle(dateAfterChangeString);
//Toast.makeText(MainActivity.this, "you clicked date", Toast.LENGTH_SHORT).show();
}
};
#Override
public Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 0473) {
String currentDateString = dynamicDate.getTitle().toString();
//DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
return new DatePickerDialog(this, myDateListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
}
return null;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_back) {
String currentDateString = dynamicDate.getTitle().toString();
//DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, -1);
Date dateDayBefore = cal.getTime();
String dateDayBeforeString = df.format(dateDayBefore);
dynamicDate.setTitle(dateDayBeforeString);
//return true;
}
if (id == R.id.action_date) {
showDialog(0473);
}
if (id == R.id.action_forward) {
String currentDateString = dynamicDate.getTitle().toString();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = null;
try {
currentDate = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, +1);
Date dateDayAfter = cal.getTime();
String dateDayAfterString = df.format(dateDayAfter);
dynamicDate.setTitle(dateDayAfterString);
//return true;
}
return super.onOptionsItemSelected(item);
}
I had used removeDialog (when back and forward buttons where pressed) for onCreateDialog to work each time the date was pressed.
I want to get the current time and compare that with time range provided by me.
for example I want to set the greeting message of Good morning if the current time is between 6:00 AM to 11:59 AM
Here is some code of my android Application
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class MainActivity extends Activity implements View.OnClickListener {
protected Calendar firstBound;
protected Calendar secondBound;
protected static Calendar cal;
protected static String timeString = null;
protected static String greetString = null;
protected static DateFormat date;
Button greetButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get a reference to the greetButton on the UI
greetButton = (Button) findViewById(R.id.greetButton);
cal = Calendar.getInstance(TimeZone.getDefault());
Date currentLocalTime = cal.getTime();
date = new SimpleDateFormat("HH:mm");
timeString = date.format(currentLocalTime);
char h1 = timeString.charAt(0);
char h2 = timeString.charAt(1);
char m1 = timeString.charAt(3);
char m2 = timeString.charAt(4);
cal.set(Calendar.HOUR,Character.getNumericValue(h1) + Character.getNumericValue(h2));
cal.set(Calendar.MINUTE,Character.getNumericValue(m1) + Character.getNumericValue(m2));
// Set the onClickListener for the greetButton to be this class.
// This requires that the class implement the View.OnClickListener callback
// the onClick() method
greetButton.setOnClickListener(this);
}
And My On Click method is
public void onClick(View v) {
TextView textMessage = (TextView) findViewById(R.id.textMessage);
EditText editFriendName = (EditText) findViewById(R.id.editFriendName);
String friendName = editFriendName.getText().toString();
switch (v.getId()) {
case R.id.greetButton:
// set the string being displayed by the TextView to the greeting
if(cal.after(setFirstBoundLimits(14, 00)) && cal.before(setSecondBoundLimits(18, 00))){
Toast.makeText(MainActivity.this, timeString, Toast.LENGTH_LONG).show();
}
// message for the friend
//textMessage.setText(getString(R.string.greetstring) + friendName + "!");
break;
default:
break;
}
}
private Calendar setFirstBoundLimits(int hh, int mm){
firstBound = Calendar.getInstance();
firstBound.set(Calendar.HOUR, hh);
firstBound.set(Calendar.MINUTE, mm);
return firstBound;
}
Period and Duration
Smart Hello
Showing Morning, afternoon, evening, night message based on Time in java
Difference in days between two dates in Java?
****Thank you...this code really worked for me
protected String getCurrentTimeMessage(){
//Date date = new Date();
Calendar cal = Calendar.getInstance();
//cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
if(hours>=6 && hours<=11){
//Toast.makeText(this, "Good Morning" + hours, Toast.LENGTH_SHORT).show();
return "Good Morning";
}else if(hours>=12 && hours<=16){
// Toast.makeText(this, "Good Afternoon"+ hours, Toast.LENGTH_SHORT).show();
return "Good Afternoon";
}else if(hours>=17 && hours<=20){
// Toast.makeText(this, "Good Evening"+ hours, Toast.LENGTH_SHORT).show();
return "Good Evening";
}else if(hours>=21 && hours<=23){
// Toast.makeText(this, "Good Night"+ hours, Toast.LENGTH_SHORT).show();
return "Good Night";
}
else if(hours >=0 && hours <= 5){
return "Good Night";
}
return null;
}
I am using datepickerdialog. it run properly on kitkat but when i run application on lollipop and when i click on edit text it opens a datepickerdialog box but when i select date it give unfortunately stop error. Below is the code for datepicker on edittext.
private void setDateTimeField() {
fromLabel.setOnClickListener(this);
toLabel.setOnClickListener(this);
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //yyyy/MM/dd HH:mm:ss
final Date date = new Date();
final String u = dateFormat.format(date);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
from1 = dateFormatter.format(newDate.getTime());
diff1 = newDate.getTimeInMillis();
long d = date.getTime();
if((newDate.getTime()).equals(date)||(newDate.getTime()).after(date)){
long d1 = (diff1 / (24 * 60 * 60 * 1000) - d / (24 * 60 * 60 * 1000)) + 1;
if(d1>30){
total.setVisibility(View.VISIBLE);
total.setText("Booking not allowed as the Date given is outside Advance Booking Period");
avail.setVisibility(View.GONE);
}
else{
total.setVisibility(View.GONE);
fromLabel.setText(from1);
toLabel.setText(null);
to=null;
avail.setVisibility(View.GONE);
from=fromLabel.getText().toString();
}
}
else{
total.setVisibility(View.VISIBLE);
total.setText("Choose date after or equals to current date");
fromLabel.setText("");
toLabel.setText(null);
from=null;
to=null;
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
fromDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
dialog.cancel();
if(type.equals("According to time"))
{
int cnt=-1;
if(from1.equals(u)){
cnt = 1;
loadTimeSpinnerDataATT(text,from,cnt);
}
else if(total.getText()=="Choose date after or equals to current date")
{
}
else if(total.getText()=="Booking not allowed as the Date given is outside Advance Booking Period")
{
}
else
{cnt = 0;
loadTimeSpinnerDataATT(text,from,cnt);
}
}
}
}
});
}
public void onClick(View view) {
if(view == fromLabel) {
fromDatePickerDialog.show();
} else if(view == toLabel) {
toDatePickerDialog.show();
}
}
public void onClose(DialogInterface dialogInterface)
{
}
}
Try it, may help you,
Date picker error resloved here
Link For Date picker
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
// for date picker
EditText m3_DateDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m3_DateDisplay = (EditText) findViewById(R.id.datepick);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show selected date
StringBuilder dateValue1 = new StringBuilder().append(day).append("-")
.append(month + 1).append("-").append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
m3_DateDisplay.setFocusable(false);
m3_DateDisplay.setInputType(InputType.TYPE_NULL);
m3_DateDisplay.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
// return new DatePickerDialog(this, pickerListener, year, month,
// day);
// ///Only Show till Date Not More than That.
DatePickerDialog dialog = new DatePickerDialog(this,
pickerListener, year, month, day);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
StringBuilder dateValue = new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
}
};
}
change minimum api-11 in manifest
I am using a DatePicker so that the user can select a date and find out the sunrise and sunset times for that particular date.
The webservice I am using requires the date to be snet in the following format dd/MM but I would like the button to show the date in the format DDth MMMM YYYY e.g 21st March 2013
Any advice on how I should I go about doing this?
Code below as requested:
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
public Spinner Locationspinner;
public DateDialogFragment frag;
public Button date;
public Calendar now;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
//Date stuff
now = Calendar.getInstance();
date = (Button)findViewById(R.id.date_button);
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
date.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
// More date stuff
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
public interface DateDialogFragmentListener{
//this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
public void updateChangedDate(int year, int month, int day);
}
public void addListenerOnSpinnerItemSelection() {
Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
Locationspinner
.setOnItemSelectedListener(new CustomOnItemSelectedListener(
this));
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(now.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
DateDialogFragment:
import java.util.Calendar;
import richgrundy.learnphotography.SunriseSunset.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
Your help would be greatly appreciated.
Please ask questions for clarification if need =)
----------------UPDATE-------------------------
I'm getting there, updated code now looks like this:
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
DateFormat format = new SimpleDateFormat("DD MM yyyy"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Just use another SimpleDateFormat to format it.
public void updateChangedDate(int year, int month, int day) {
DateFormat format = new SimpleDateFormat("DD MM YYYY"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime());
}
Unfortunately there is nothing provided by Java to automatically get the proper suffix for ordinal dates (2nd, 13*th*, 21st, etc.)
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
now.set(year, month, day);
date.setText(DateFormat.format("dd MMMM yyyy", now));
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Change
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
to
date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
public void showDialog()
{
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener()
{
public void updateChangedDate(int year, int month, int day)
{
String dateFormate = "dd'" + getDayOfMonthSuffix(day) +"' MM yyyy";
DateFormat format = new SimpleDateFormat(dateFormate); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31), "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
I copy above getDayOfMonthSuffix function from the below link
getDayOfMonthSuffix