Here dob is String value . How I will get a particular value from String. Please check my code I mention there were I need it.
public class MainActivity extends AppCompatActivity {
private EditText editTextDate;
private Button mButton;
private static final String DATE_FORMAT = "dd/MM/YYYY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
btnClick();
}
private void initView() {
editTextDate = findViewById(R.id.date);
}
private void btnClick() {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String dob = editTextDate.getText().toString();
// dob is is a date like 25/05/1995
// I want to 1995 value. What will i do??
}
});
}
}
Although, you can go for splitting the string using a regex, but here, this is what you need to learn. SimpleDateFormat. This will give you a lot more control especially when you'll use time with it.
Java
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date yourDate = format.parse("25/05/1995");
Calendar yourCal = new Calendar.getInstance();
yourCal.setTime(yourDate);
Log.d("Tag","Day : "+ yourCal.get(Calendar.DAY_OF_MONTH));
Log.d("Tag","Month: " + yourCal.get(Calendar.MONTH) + 1);
Log.d("Tag","Year: " + yourCal.get(Calendar.YEAR));
Kotlin
val format = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val yourDate = format.parse("25/05/1995")
val yourCal: Calendar = Calendar.getInstance()
yourCal.time = yourDate!!
Log.d("Tag", "Day : " + yourCal[Calendar.DAY_OF_MONTH])
Log.d("Tag", "Month: " + yourCal.get(Calendar.MONTH) + 1)
Log.d("Tag", "Year: " + yourCal.get(Calendar.YEAR))
Remember, month starts from 0 for January so you've to +1 in that, And capital 'M' denotes month in java where as small 'm' denotes minutes. There are lots of formats for SimpleDateFormat, you can use any of them.
Just use the appropriate function.
String#split()
String dob = editTextDate.getText().split("/")[2]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When click on next button i need to set the next month to text view without opening the month picker and similarly to previous button also. Please can any one help me.
Here is my code
Date today = Calendar.getInstance().getTime();//getting date
SimpleDateFormat formatter = new SimpleDateFormat("MMM-YYYY");
String date = formatter.format(today);
Calendar today1 = Calendar.getInstance();
textView.setText(date);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String dateString = textView.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-YYYY");
//Date date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Get month,year from Calender as String , then parse it as LocalDate then format it through formater .
Example-
public class MainActivity extends AppCompatActivity {
private TextView monthView;
Button next, previous;
public static LocalDate localDate;
private String dateFormat;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
monthView = findViewById(R.id.tvLDate);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
getDate();
next.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.plusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
previous.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.minusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void getDate() {
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
String year = String.valueOf(calendar.get(Calendar.YEAR));
dateFormat = "01/" + month + "/" + year;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
localDate = LocalDate.parse(dateFormat, formatter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String monthFormat(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM");
return date.format(formatter);
}
}
what you could do is ->
// Get an instance of calendar and set the required Date()
val calendar = Calendar.getInstance()
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] += 1 // This will give you the currently selected month +1
}
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] -= 1 // This will give you the currently selected month -1
}
public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!
I am using Material DateTime picker for choosing date and time. Its working fine, but in onTimeSetListener method it returns hourOfTheDay in 24 hours format.
I want to show it it 12 hour format for that I used the if condition where hours are greater than 12 then it should show PM, but the hour number dose not change.
How can I change this?
public class TransportFragment extends Fragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {
private OnFragmentInteractionListener mListener;
private EditText mEditTxt_From,mEditTxt_To,mEditTxt_DateTime;
int PLACE_PICKER_REQUEST = 1;
private static final String TAG = "PlacePickerSample";
private static final int REQUEST_PLACE_PICKER_FROM = 1;
private static final int REQUEST_PLACE_PICKER_TO = 2;
private String mDate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transport, container, false);
mEditTxt_From = (EditText) view.findViewById(R.id.editTextFrom);
mEditTxt_To = (EditText) view.findViewById(R.id.editTextTo);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setVersion(DatePickerDialog.Version.VERSION_2);
dpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
dpd.show(getFragmentManager(), "Datepickerdialog");
}
});
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mDate = dayOfMonth+"/"+(++monthOfYear)+"/"+year;
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
tpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
#Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
String minuteString = minute < 10 ? "0"+minute : ""+minute;
String secondString = second < 10 ? "0"+second : ""+second;
String time;
if(hourOfDay > 12)
{
time = hourOfDay + ":" + minuteString + " PM";
}
else {
time = hourOfDay + ":" + minuteString + " AM";
}
mEditTxt_DateTime.setText(mDate + " " + time );
}
}
Please help. Thank you.
I think your if statement is invalid:
if (hourOfDay > 12) {
time = (hourOfDay - 12) + ":" + minuteString + " PM";
} else {
...
}
You do not need to reinvent the wheel. In particular, if your app is working with dates and times, you should consider getting the ThreeTenABP library and using the modern Java date and time classes. One of these, LocalTime, solves your task in two lines:
DateTimeFormatter twelveHourTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String time = LocalTime.of(hourOfDay, minute, second)
.format(twelveHourTimeFormatter);
Once you move to Java 8 the classes are built-in and you can discard the library.
In case you don’t want the dependency on one more external library, you can obtain the same with the outdated classes GregorianCalendar, Date and SimpleDateFormat, only it will be less elegant and far from future-proof.
Links
ThreeTenABP
Question: How to use ThreeTenABP in Android Project
No matter what variation of code to display the date is used it won't set the text of the TextView.
public void setDate (View view){
TextView dateView;
Date dNow = new Date();
String str = String.format("Current Date : %tc", dNow);
dateView = (TextView)findViewById(R.id.date_Text_View);
dateView.setText("The date is" + str);
}
Cheers,
Harris
After creating TextView onCreate(), you should call setDate() method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
TextView dateView = (TextView)findViewById(R.id.date_Text_View);
setDate(dateView);
}
public void setDate (TextView view){
String str = String.format("%tc", new Date());
view.setText("The date is " + str);
}
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;
}