I have the following code below in the server stored as gmt and would like it to change based on android device timezone.I am getting wrong value unable to figure out the mistake.I really appreciate any help.
Thanks in Advance.
public class MainActivity extends Activity {
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String d="2014-01-14 16:28:50";
t=(TextView)findViewById(R.id.textView1);
Timestamp ts = Timestamp.valueOf(d);
long tsTime1 = ts.getTime();
String r=getDate(tsTime1);
t.setText(r);
}
private String getDate(long timeStamp){
SimpleDateFormat objFormatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
objFormatter.setTimeZone(TimeZone.getDefault());
Calendar objCalendar =
Calendar.getInstance(TimeZone.getDefault());
objCalendar.setTimeInMillis(timeStamp*1000);//edit
String result = objFormatter.format(objCalendar.getTime());
objCalendar.clear();
return result;
}
}
public String TimeFormating(String Time)
{
SimpleDateFormat format_before = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
SimpleDateFormat format_to_Convert = new SimpleDateFormat("hh:mm a",Locale.getDefault());
format_before.setTimeZone(TimeZone.getTimeZone("GMT"));
format_to_Convert.setTimeZone(TimeZone.getDefault());
Date time = null;
try
{
time = format_before.parse(Time);
} catch (ParseException e)
{
e.printStackTrace();
}
return format_to_Convert.format(time).toLowerCase(Locale.getDefault());
}
Related
There are three buttons like prev, next, today. If you click on them, the data should go to the string containing calender data formattedDate. String formattedDate = df.format(c.getTime());
`prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
}
});
private void requestHomeData2() {
ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getApiUrl());
callbackCall2 = apiInterface.getDate(formattedDate,AppConfig.REST_API_KEY);
this.callbackCall2.enqueue(new Callback<Callbackdate>() {
public void onResponse(Call<Callbackdate> call, Response<Callbackdate> response) {
Callbackdate responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
onFailRequest();
return;
}
displayData2(responseHome);
swipeProgress(false);
lyt_main_content.setVisibility(View.VISIBLE);
}
public void onFailure(Call<Callbackdate> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
onFailRequest();
}
}
});
}``
FormattedDate error how to fix this error image
Use this two line above the error line.
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
I need to format date and time in the RemoteViewsFactory class. I know how to use DateFormat/SimpleDate Format. I'm doing it like in the thread below but the app keeps stopping when pressing on the widget on a physical device: remoteViews.setTextViewText(R.id.tvTaskDay, DateFormat.getDateInstance().format(task.getDay()));
Android - ListView items inside app widget not selectable
I'm also formatting in the parent activity and it works. Is it possible to reference the SimpleDateFormat code from there? Thank you in advance.
P.S. Error message.
My RemoteViewsFactory class:
public class ScheduleWidgetViewFactory implements RemoteViewsService.RemoteViewsFactory
{
private ArrayList<Schedule> mScheduleList;
private Context mContext;
public ScheduleWidgetViewFactory(Context context)
{
mContext = context;
}
#Override
public void onCreate()
{
}
#Override
public void onDataSetChanged()
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
Gson gson = new Gson();
Type type = new TypeToken<List<Schedule>>() {}.getType();
String gsonString = sharedPreferences.getString("ScheduleList_Widget", "");
mScheduleList = gson.fromJson(gsonString, type);
}
#Override
public int getCount()
{
return mScheduleList.size();
}
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, DateFormat.getDateInstance().format(schedule.getExpectedArrival()));
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
#Override
public int getViewTypeCount()
{
return 1;
}
Parent Activity:
#Override
public void returnScheduleData(ArrayList<Schedule> simpleJsonScheduleData)
{
if (simpleJsonScheduleData.size() > 0)
{
scheduleAdapter = new ScheduleAdapter(simpleJsonScheduleData, StationScheduleActivity.this);
scheduleArrayList = simpleJsonScheduleData;
mScheduleRecyclerView.setAdapter(scheduleAdapter);
scheduleAdapter.setScheduleList(scheduleArrayList);
stationArrival = scheduleArrayList.get(0);
stationShareStationName = stationArrival.getStationScheduleName();
stationShareArrivalTime = stationArrival.getExpectedArrival();
stationShareDirection = stationArrival.getDirectionTowards();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(stationArrival.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationShareArrivalTime = finalDate;
//Store Schedule Info in SharedPreferences
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(scheduleArrayList);
prefsEditor.putString("ScheduleList_Widget", json);
prefsEditor.apply();
}
else
{
emptySchedule.setVisibility(View.VISIBLE);
}
In case anyone else has is stuck on this. As Mike M. pointed out in the comments, the DateFormat code structure in RemoteViewsFactory is the same as everywhere else.
private String stationWidgetArrivalTime;
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(schedule.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationWidgetArrivalTime = finalDate;
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, stationWidgetArrivalTime);
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
I have two datepickers in my activity.
I want startdate of datePickerB dialog to be updated automatically based on date selected in datePickerA dialog.
I use setMinDate for datePickerB. setMinDate works fine for the very first time. But couldn't update or reset the mindate of datePickerB for consecutive updates in datePickerA. Kindly help.
Searched for all possible solutions but of no use. Kindly help
Below is my code. The code used in oncreate gets executed , but further setMinDate function called in HandleResponse ( this is the function that gets called once datepickerA is set )
//On OnCreate
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
long t = tomorrow.getTime();
fromDatePicker.getDatePicker().setMinDate(t);
//
toDatePicker.getDatePicker().setMinDate(t);
public void HandleResponse(Response response)
{
String sqlRes = "";
try {
String sResJson = response.body().string();
JSONObject jReader = new JSONObject(sResJson);
JSONObject jRes = jReader.getJSONObject("Result");
sqlRes = jRes.getString("res");
final int sqlMilkQty = jRes.getInt("qty");
String enddate = jRes.getString("date");
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(enddate);
} catch (ParseException e) {
e.printStackTrace();
}
if (d != null && fromDate!= null) {
long t = d.getTime();
long t1 = fromDate.getTime();
toDatePicker.getDatePicker().setMinDate(t1);
toDatePicker.getDatePicker().setMaxDate(t);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
if (sqlRes.equals("PASS"))
{
mainHandler.post(new Runnable() {
#Override
public void run() {
milkQuantity = sqlMilkQty;
txtMilkQuantity.setText(String.valueOf(milkQuantity));
}
});
}
else {
}
} catch (IOException e) {
DisplayError();
}
catch (JSONException e) {
DisplayError();
}
}
I check a webside if new items have been posted and if yes a string value "new" is added to these items.
Now the long value "date" always stays on -1, as a result the string value "new" is added after every item, also for items added for example yesterday.
"new" should not be shown for values older then today, please help.
Thank you.
public class TopicView extends LinearLayout implements LoadTopicImageCallback {
private LoadTopicImageTask topicImageTask = null;
private boolean newItem = false;
private long date = -1;
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
}
public TopicView(final Context context, final Topic topic, final String suffix) {
super(context);
init(topic);
final long latest = new Settings(context).getLatest(suffix);
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
//String new gets added//
if (latest == -1 || date > latest) {
findViewById(R.id.topic_view_new).setVisibility(View.VISIBLE);
newItem = true;
}
}
public boolean isNewItem() {
return newItem;
}
public long getDate() {
return date;
}
EDIT:
public static String formatDate(final long dt) {
return formatDate(new Date(dt));
}
public static String formatDate(final Date date) {
final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
return df.format(date);
}
public static final Date parseDate(final String date) throws ParseException {
final String pattern = "EEE MMM dd, yyyy h:mm a";
return parseDate(date, pattern);
}
public static final Date parseDate(final String date, final String pattern)
throws ParseException {
final SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
return format.parse(date);
}
Unless you're sure that you're calling the second constructor, you never initialise the date here:
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
// add some initialisation for "date" here
}
And even if you are, it would've been helpful to see that small part of code too.
As an aside, can I point out that it's fine to consume exceptions, but even a shred of debug output can help you in the long run. Maybe change
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
to:
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
e.printStackTrace(); // Or some log that your define yourself.
}
I have a DateTimehelper.class in which i have performed some date related operation and the code was working fine until i get issue from customer that they are getting date in wrong format.following is my class:
public class DateTimeHelper {
private static Calendar cal;
public static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static DateFormat shortDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static DateFormat shortDateFormatterWithSlash = new SimpleDateFormat("dd/MM/yyyy");
public static DateFormat dateFormat_dd_MM_yyyy = new SimpleDateFormat("dd-MM-yyyy");
DateTimeHelper helper;
/**
* set UTC Date to the calendar instance
*
* #param strDate
* date to set
*/
public static void setDate(String strDate) {
try {
Date date = (Date) formatter.parse(strDate);
cal = Calendar.getInstance();
cal.setTime(date);
updateDateTime();
}
catch (ParseException e) {
e.printStackTrace();
}
}
/**
* update date every 1 second
*/
private static void updateDateTime() {
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
try {
cal.add(Calendar.SECOND, 1);
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/***
* get updated date from calendar in custom date format
*
* #return date
*/
public static String getDate() {
String strDate = null;
try {
strDate = formatter.format(cal.getTime());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strDate;
}
}
When See the logs I found date in format:2014-0011-25 04:45:38 which is completely wrong I guess because month should be 11 instead of 0011.
But when I tried to validate this date using the below function;it says that date is valid.
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
How can it be a valid date?
Why I am getting date in wrong format?
This issue is very random as it is reported by only user but I am very surprised by the behavior of SimpleDateFormater and Calendar API
Please help.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try this see if it works