Have TextView show day of week as letters not integer - android

I have a textview which shows the day of the week as an integer (0-7). I would prefer if it could convert that to a string, which could then be shown in a TextView. My code is below. Also, how can I make it so the TextViews update the time, date, etc. (it only shows the time the app is opened)? Thanks in advance.
MainActivity.java:
package press.linx.calendar;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView day = (TextView)findViewById(R.id.day);
TextView month = (TextView)findViewById(R.id.month);
TextView year = (TextView)findViewById(R.id.year);
TextView time = (TextView)findViewById(R.id.time);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
day.setText("" + today.monthDay); // Day of the month (0-31)
month.setText("" + today.month); // Month (0-11)
year.setText("" + today.year); // Year
time.setText("" + today.format("%k:%M")); // Current time
}
}
UPDATE: I got it using this piece of code:
final Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MMM"); // 3-letter month name & 2-char day of month
TextView datetxt = (TextView) findViewById(R.id.nameofyourtextview);
datetxt.setText(formatter.format(calendar.getTime()));

To format your Time:
Time time = new Time();
time.format("%A");
It returns name of day in week (Sunday, Friday..) - see description of format string (It's a PHP man page, but the symbols are same and it's well-aranged)
In order to make textViews updated every second you have to use Timer and TimerTask.
Define UpdateTimeTask:
class UpdateTimeTask extends TimerTask {
public void run() {
// Update time, must be called using runOnUiThread
}
}
and then set timer:
Timer timer = new Timer();
TimerTask updateTime = new UpdateTimeTask();
timer.scheduleAtFixedRate(updateTime, 0, 1000);

I assume you are looking for the date to be displayed in the below format.
You can use the below
Date now = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
System.out.println("Format : " + dateFormatter.format(now));
Output
Format : Thursday, April 25, 2013
Few helpful links
http://www.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html
http://www.roseindia.net/tutorial/java/core/convertDateToWords.html

To get the current day of the week (i.e. Monday, Tuesday, Wednesday, etc.) try:
DateFormat fmt = new SimpleDateFormat( "EEEE" );
fmt.format( new java.util.Date() );

Try this
month.setText(getMonth(today.month));
day.setText(getWeek(today.monthDay));
method to get month based on month number
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month];
}
method to get week based on week number
public String getWeek(int weekno) {
return new DateFormatSymbols().getWeekdays()[weekno];
}

Do you mean display as Mon, Tue, Wed,.... ?
Use this format.
SimpleDateFormat curFormatDate = new SimpleDateFormat("EEE");

Related

Get week start and end days from week number

I want to get the start and end dates of a given week number. I have tried the following code but it always returns the same date (the current week)
val c: Calendar = Calendar.getInstance()
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val firstDayOfWeek = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDayOfWeek)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
I solved it by calling c.time an extra time before using it. Here's the working code :
val c: Calendar = Calendar.getInstance()//Locale.getDefault())
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val t = c.time;
val firstDay = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDay)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK,firstDay+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
Cannot understand why it works, tried it after reading this https://developer.android.com/reference/java/util/Calendar#field-manipulation
You must be missing something or making some basic mistake. Given below is the proof:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
int week = 39;
Calendar c = Calendar.getInstance();
c.set(Calendar.WEEK_OF_YEAR, week);
int firstDayOfWeek = c.getFirstDayOfWeek();
// Start date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
String startDate = sdf.format(c.getTime());
System.out.println(startDate);
// End date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + 6);
String endDate = sdf.format(c.getTime());
System.out.println(endDate);
}
}
Output:
2020-09-21
2020-09-27
Note: I do not know Kotlin but AFAIK, you can run Java code also in Kotlin. If you want to stick to Kotlin syntax, I hope you should be able to convert it easily into Kotlin syntax.

How to get the current time on a button click?

I know am not the first to ask this ,What I need to do is when I close the current activity by clicking on a button ,I want to show the current time .
This will have the following validation.
1,In the current activity I have a timepicker if I select any time any click on the save button it will show the sellected time and closing the current activity.
2,If I am not selected any time from timepicker and On the save button click I want to show the current time .
For me the First one is working fine but the second one is always showing null.
TimePicker Time :
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker timePicker, int i, int i1) {
int hour = i % 12;
mselectedTime = (String.format("%02d:%02d %s", hour == 0 ? 12 : hour, i1, i < 12 ? "AM" : "PM"));
}
});
code :
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mselectedTime == "null"){
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
Toast.makeText(getApplicationContext(),"Time Is :" + dateFormat, Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), mselectedTime, Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(CreateAlarm.this, AlarmActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_out, R.anim.slide_out);
}
});
Here the second Toast is showing the time ,but First toast is always showing empty .I need to show the time as 04:50 Am/Pm format in the first toast
Can anyone tell me where I did the mistake .
In the second toast you need to reacquire the time, then add it to the toast, not the SimpleDateFormat. Here's the code:
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String output = dateFormat.format(currentTime);
Toast.makeText(getApplicationContext(),"Time Is :" + output, Toast.LENGTH_LONG).show();
Using Calendar instance you can get current hour and minutes
Calendar c;
private int mhour;
private int mminute;
c = Calendar.getInstance();
mhour = c.get(Calendar.HOUR);
mminute = c.get(Calendar.MINUTE);
// you will get current hour and minutes of device time
also refer to this
DateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String dateString = dateFormat.format(new Date()).toString();
Toast.makeText(this,"Current time :"+ dateString,Toast.LENGTH_LONG).show();
and you may have imported wrong packages use.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

How get Date and Time from Timestamp to different TextView

I have timestamp in DataBase like this: 1472373943.
In my Adapter I would like set Date & Time to different TextView.
For Example:
How to separate the date and time? Thanks.
First, what is your input? In your question, it looks like 1472373943, So I don't know which is time, and date position in that string. For simple, let assume that you have a sample date and time as follows:
String date = "12/8/2012";
String time = "11:25 am";
So, to convert it. The simple way is
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
String date = "12/8/2012";
String time = "11:25 am";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
Date dt = df.parse(date + " " + time);
Calendar ca = Calendar.getInstance();
ca.setTime(dt);
System.out.println(ca.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You can do that by using two different SimpleDateFormatters on the same Date object, one for the date and the other for the hours. "YYYY/MM/DD" and the other is "HH:mm a", just for an example.

Comparing two times in android

I have tried with the below code to compare two times:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date inTime = sdf.parse("11:00");
Date outTime = sdf.parse("10:00");
if(inTime.compareTo(outTime) > 0){
Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
}
Above code is working fine.
But if I give in time as 11:00 and out time as 12:00, I am getting above toast message.
I am getting above toast message if I give out time from 12:00 to 12:59. In other cases above code is working fine.
Where I am doing wrong. Please help me.
Change SimpleDateFormat like below...
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Below are the patterns:
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
This will work....
tl;dr
Use java.time.
LocalTime
.parse( "12:00" )
.isAfter(
LocalTime.parse( "11:00" )
)
java.time
You have three problems:
You are using terrible old date-time classes (Date & SimpleDateFormat) that were supplanted years ago by the modern java.time classes.
Your format of hh:mm should have been uppercase for 24-hour clock rather than 12-hour clock: HH:mm.
You are inappropriately trying to represent a time-of-day with a class meant for date-with-time-of-day values.
Use LocalTime. This class represents a time-of-day without a date and without a time zone.
LocalTime start = LocalTime.parse( "11:00" ) ;
LocalTime stop = LocalTime.parse( "12:00" ) ;
You can compare.
boolean isStopAfterStart = stop.isAfter( start ) ;
Calculate the elapsed time as a Duration.
Duration d = Duration.between( start , stop ) ;
d.toString(): PT1H
You can also ask the Duration if it is negative, as another way to detect the stop time being before the start.
boolean isStopBeforeStart = d.isNegative() ;
Caveat: Working on time-of-day without the context of a date and a time zone can produce unrealistic results. That approach ignores the anomalies that occur in time zones such as Daylight Saving Time (DST) and other shifts to the wall-clock time used by the people of a particular region. An hour can repeat, or be skipped. A day can be 23, 23.5, 23.75, 25, or other number of hours long.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Ketan Ramani on 20/9/18.
*/
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static EditText text;
private static TextView textTv;
private static Date startDate = null;
private static Date fromTime = null;
public static TimePickerFragment getInstance(View view) {
if (view instanceof EditText) {
text = (EditText) view;
} else if (view instanceof TextView) {
textTv = (TextView) view;
}
return new TimePickerFragment();
}
public static TimePickerFragment getInstance(View view, Date fromTimeCalendar) {
if (view instanceof EditText) {
text = (EditText) view;
} else if (view instanceof TextView) {
textTv = (TextView) view;
}
fromTime = fromTimeCalendar;
return new TimePickerFragment();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, true/*DateFormat.is24HourFormat(getActivity())*/);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (fromTime != null) {
Calendar fromTimeCal = Calendar.getInstance();
fromTimeCal.setTime(fromTime);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date toDate = null;
try {
toDate = sdf.parse(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar toTimeCal = Calendar.getInstance();
toTimeCal.setTime(toDate);
if (toTimeCal.getTimeInMillis()<fromTimeCal.getTimeInMillis()){
Helper.showToast(getActivity(),"To time can't less than from time");
} else {
if (text != null) {
text.setText(getFormatedTime(hourOfDay, minute));
} else if (textTv != null) {
textTv.setText(getFormatedTime(hourOfDay, minute));
}
}
} else {
if (text != null) {
text.setText(getFormatedTime(hourOfDay, minute));
} else if (textTv != null) {
textTv.setText(getFormatedTime(hourOfDay, minute));
}
}
}
private String getFormatedTime(int hourOfDay, int minute) {
int hour, min;
Calendar datetime = Calendar.getInstance();
String am_pm = "";
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
hourOfDay = hourOfDay > 12 ? hourOfDay - 12 : hourOfDay;
hour = hourOfDay > 9 ? hourOfDay : hourOfDay;
min = minute > 9 ? minute : minute;
return String.format("%02d", hour) + ":" + String.format("%02d", min) + " " + am_pm;
}
public void showTimePickerDialog(Context context, View view) {
DialogFragment newFragment = TimePickerFragment.getInstance(view);
newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
}
public void showTimePickerDialog(Context context, View view, Date fromTime) {
DialogFragment newFragment = TimePickerFragment.getInstance(view, fromTime);
newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
}
}
Use
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_from_time:
TimePickerFragment fromTime = new TimePickerFragment();
fromTime.showTimePickerDialog(context, v, null);
mToTimeEt.setText("Select To Time");
break;
case R.id.et_to_time:
if(mFromTimeEt.getText().toString().equalsIgnoreCase("Select From Time")){
Helper.showToast(context,"Please, select from time first");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date fromDate = null;
try {
fromDate = sdf.parse(mFromTimeEt.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
TimePickerFragment toTime = new TimePickerFragment();
toTime.showTimePickerDialog(context, v, fromDate);
}
break;
}
}
This class will work for EditText and TextView and set time to respected EditText or TextView if To time is After From Time in HH:mm a Format
If you are using 24 hour time format then use kk instead of HH.
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");

problem while printing date and time in android

I want to print date and in android.
Once I run it for first time its getting correct time and date. But When I install in phone and run it its not getting correct. Its giving only same result when I have install it.
my code is here:
package com.datePrint;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DatePrint extends Activity {
/** Called when the activity is first created. */
static Calendar cal = new GregorianCalendar();
static int hour = cal.get(Calendar.HOUR);
static int minute = cal.get(Calendar.MINUTE);
static int second = cal.get(Calendar.SECOND);
static int year = cal.get(Calendar.YEAR);
static int month = cal.get(Calendar.MONTH)+1;
static int day = cal.get(Calendar.DATE);
static String date = day+"_"+month+"_"+year+"_";
static String Current_Time = date+ hour + "_" + minute + "_" + second;
public static String OUTPUT_FILE = "/sdcard/"+Current_Time+".mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText(Current_Time);
setContentView(tv);
}
}
can anybody help me to solve this problem
thanks in advance
You have declared all variables as static, so first remove it from all.
You should refer and understand the concept of static.
I am sure that the API level is different in your case. I have faced the same issue few time back. When I run on 1.6 device it work fine but not on 2.1 emulator.
try this code.\
java.text.SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy");
SimpleDateFormat sdfDestination = new SimpleDateFormat("E MMM dd");
java.util.Calendar cal = Calendar.getInstance(new SimpleTimeZone(0,
"GMT+5000"));
TimeZone timeZone = TimeZone.getDefault();
format.setTimeZone(timeZone);
format.setCalendar(cal);
java.util.Date date = null;
String tmp ="";
try {
date = format.parse(EditProfile.dateOFBirth);
Log.v("A", "Date Of Birth ..." + date);
Calendar tmpCal = Calendar.getInstance();
tmpCal.setTime(date);
tmp = sdfDestination.format(date) + " 00:00:00 IST "+tmpCal.get(Calendar.YEAR);
Log.v("A", "Date Of Birth new Date..." + tmp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#PM has it for the most part, but didn't explain why and missed one key point: An activity keeps running until something kills it (either by explicit shutdown which you didn;t provide for, by the OS killing it to release resources, or Force Close from the application services panel), so "running" it a second time just reactivates it with the same values still loaded into the static variables. If you force close it, the next activation will recreate it with a new time, which it will then retain until again Force Close-d.
And the missing key point is that you're doing it in onCreate, so even without static variables it will only happen the once. You need to either do it on activate or arrange for exiting to shut down the Activity.

Categories

Resources