problem while printing date and time in android - 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.

Related

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.

Cant fetch current time, date showing year as 1970

public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
LINE 5:
private String compareStringOne = String.valueOf(SetTimeActivity.intFromTimeH)+ ":"+ String.valueOf(SetTimeActivity.intFromTimeM) ;
LINE 6:
private String compareStringTwo = String.valueOf(SetTimeActivity.intToTimeH) + ":"+ String.valueOf(SetTimeActivity.intToTimeM);
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates()
{
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if (!(dateCompareOne.before( date ) && dateCompareTwo.after(date))) {
....
I am trying to check if current time falls between the specified time. For that I am converting the specified time into strings first (in Line5 & Line6). Even though I get the integer values correct, the string formed always shows "0:0".
Also, the year is shown as 1970 (The date & the day shown are wrong as well).
I need to get the current time. What am I doing wrong?
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
The parseDate() function returns the time elapsed since the 1st of January 1970. This is known as the Unix Epoch, and it's how all time is represented in Unix computers. By running the parseDate function on a string containing just hours and minutes, you're creating a Date object which represents a time HH:mm past the first of January 1970.
Your code is using a really odd way of getting the current time. Converting a Calendar to two ints, then to a string and finally parsing back to a Date is going to be inefficient and open you up to all sorts of needless errors.
When you initialise a new Date object it is automatically assigned the time of initialisation. Therefore:
Date d = new Date();
would result in d being the moment of initialisation (that is, this year, month, day, hour, minute, second and microsecond). Then you can just use Date.after() and Date.before().
If you still want to do it via the Calendar method, then you'd be better served by:
cal = Calendar.getInstance();
Date d = cal.getTime();
It may be that you've got other issues, but it's worth doing it properly first. When you pass data by writing it as a string (especially when it's time related, with all sorts of ambiguities about what "12" actually represents) you lose all the advantages that language typing gives you.
this code help you
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE); if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = df.format(c.getTime());
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
If you already work with Date objects why not using the Date.after(...) and Date.before(...) methods.

Joda Time on Android not computing correctly

So, I am trying to computer the difference between two dates in time, and out puting that difference in days, hours, and minutes. I've been running this sample code just as a java console application and it works fine, however, when I try to do the same thing in Android, I get garbage data. Is Joda Time too complex for Android? Should I try out Date4j as an alternative?
import java.util.; import org.joda.;
import org.joda.time.DateTime;
public class time {
//(5000);
final static long MILLIS_IN_DAY = 86400000;
final static long MILLIS_IN_HOUR = 3600000;
final static long MILLIS_IN_MINUTE = 60000;
public static void main(String[] args){
long day, hour, minute;
//MAKE SURE TO CHECK IF USER SET(LATER)
// DateTime(2013,9,12,0,0)
DateTime d1 = new DateTime(2013,9,17,0,0);
DateTime d2 = new DateTime(2013,9,12,21,30);
//long date = d2.getMillis();
DateTime d3 = new DateTime();
long diffInMillis = d3.getMillis() - d1.getMillis();
minute = (diffInMillis/MILLIS_IN_MINUTE)%60;
hour = (diffInMillis/MILLIS_IN_HOUR)%24;
day = (diffInMillis/MILLIS_IN_DAY);
System.out.println(Long.toString(d1.getMillis()));
System.out.println(Long.toString(d2.getMillis()));
System.out.println(Long.toString(d3.getMillis()));
System.out.println(Long.toString(diffInMillis));
System.out.println("Minutes:");
System.out.println(Long.toString(minute));
System.out.println("Hours:");
System.out.println(Long.toString(hour));
System.out.println("Days:");
System.out.println(Long.toString(day));
}
}
Don't calculate this values manually. Calculate with Joda-Time methods. There is no reason to use Joda and don't use Joda's methods
E.g.
with Days, Hours, Mintes
System.out.println("Minutes:");
System.out.println(Minutes.minutesBetween(d2, d1).getMinutes() % 60);
System.out.println("Hours:");
System.out.println(Hours.hoursBetween(d2, d1).getHours() % 24);
System.out.println("Days:");
System.out.println(Days.daysBetween(d2, d1).getDays());
or with Period
Period period = new Period(d2, d1);
System.out.println("Minutes:");
System.out.println(period.getMinutes());
System.out.println("Hours:");
System.out.println(period.getHours());
System.out.println("Days:");
System.out.println(period.getDays());

Have TextView show day of week as letters not integer

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");

Categories

Resources