Good day.I am building an chat application.For purpose i decided to put a date of message had been sent.No wounder that in different countries the date must show different.For example let's take 2 different countries and assume the difference between them are 2 hours.CountryX and CountryY.The user send message from CountryX which time is lets say 15:00.I am saving this on server with exact timezone time as user sent,exactly 15:00 as CountryX.Second user receives the message in CountryY which is more in 2 hours from CountryX,so basically The time which I MUST show in CountryY must be 17:00.This is the issue.How can i convert an already received time with known timezone to local in order to show correct?I did google a lot but all i came up,were solutions where you would simply just get an time for exact country,and not convert the CountryX sent Time to CountryY local time to show it correctly in CountryY.Please can you provide an help?Thank you very much beforehand.
For everyone suffering because of this.I have ended up creating my own class with my own logic and it works flawlessly and as an extra bonus couple of handy methods with time
public class Time {
public static String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
if (month < 10) {
String finalMonth = "0" + month;
finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
}
return finalFormat;
}
public static String convertToLocalTime(String timeToConvert) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
Date parsed;
try {
parsed = sourceFormat.parse(timeToConvert);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
return result;
}
public static String getTimeZone() {
return TimeZone.getDefault().getID();
}
}
Related
My code saves a string from edit text every time I press a button. But If I type the same string again, It would save it regardless. How do I prevent it from saving if it has been saved before already?
HistoryHelper file = new HistoryHelper(getBaseContext());
// get date
Calendar c = Calendar.getInstance();
int date = c.get(Calendar.DATE);
int month = c.get(Calendar.MONTH) + 1;// fixes wrong month
int year = c.get(Calendar.YEAR);
file.writeToSD("Date: " + year + "-" + month + "-" + date);
// get string
file.writeToSD(NEWLINK.toString());
// leave a blank line space
file.writeToSD("".toString());
//When user clicks "other".
public void setDate(View view) {
DateTime dateTime=new DateTime();
new DatePickerDialog(CreateEventActivity.this, listener, dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfWeek()).show();
}
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
DateTime eventDate = new DateTime();
eventDate.withYear(year);
eventDate.withMonthOfYear(monthOfYear + 1);
eventDate.withDayOfMonth(dayOfMonth);
time = eventDate;
Context appContext = getApplicationContext();
Toast.makeText(appContext, dayOfMonth + "/" + (monthOfYear + 1) + "/" + year + "," +eventDate.dayOfWeek().getAsText(), Toast.LENGTH_LONG).show();
dateTxt.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
dayTxt.setText(eventDate.dayOfWeek().getAsText());
otherButton.setBackgroundColor(Color.parseColor("#77B3FC"));
todayButton.setBackgroundColor(Color.parseColor("#DBDBDB"));
tomorrowButton.setBackgroundColor(Color.parseColor("#DBDBDB"));
}
};
I have a problem with this part: eventDate.dayOfWeek().getAsText()
It shows the wrong day of the week, but the date in numbers is fine.
(Just started using Joda-Time so I'm not sure about it...)
EDIT:
The date in numbers like: 23.7.16 is printed correctly, But I want it to show which day is it in the week, like "Monday"... I've noticed it always writes today's name. In the toast and in the text view...
For example, for couple of different dates it will show:
23.6.16, Friday|
15.7.16, Friday|
30.8.17, Friday
the others data are right because you are using the data of the DataPicker and not of the JodaTime, may have some error in your construction try:
DateTime eventDate = new DateTime(year,monthOfYear+1,dayOfMonth,0,0,0);
the 0,0,0 are hours, minutes and seconds, remove the 3 lines :
eventDate.withYear(year);
eventDate.withMonthOfYear(monthOfYear + 1);
eventDate.withDayOfMonth(dayOfMonth);
all my code is in timer and it tik every 2 seconds
I have 3 different times
1) Time from the time picker(sTime).
2) Get Current time of my phone(cTime).
3) Expiry Time - (for creating range between timepicker's time and expiry time) (rTime).
I want to silent my phone when cTime is equal or after sTime
and turn back my phone profile to normal when cTime is equal or after rTime
but i cannot achieve this. i have done my coding and i think logic is fine but why its not working. please help me in this regard.
Here is my code
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String savedTime = sHour + ":" + sMin;
Date sTime = sdf.parse(savedTime);
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour + ":" + currentMin;
Date cTime = sdf.parse(currentTime);
int rangeHour = sHour;
int rangeMin = sMin + 1;
Date rTime = sdf.parse(rangeHour + ":" + rangeMin);
if (cTime.after(sTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.e("res", "Silent Mode Timing");
}
if (cTime.after(rTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.e("res", "Normal Mode Timing");
}
} catch (Exception ex) {
Log.e("res", ex.toString());
}
Ok, I have a suggestion. The method 'after' of Date class compare two long values in milliseconds. When you get current time milliseconds value it calculate as current year + current month + current day and hour etc. (or something like this). And when you get milliseconds of you savedTime it calculates incorrect because you not specify full Date (year, etc). I mean that you startTime incorrect when it convert in long milliseconds value in Date.after method. try to change you algorithm to work wit long timestamp, not with Date. for example current time is System.currentTimeMillis(). I hope it help. Sorry for my English
Ok, try to use something like this:
private void compareTime(final String year, final String day, final String hour, final String month, final String minutes) {
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:dd:mm:yy");
final String savedTimeValue = hour + ":" + minutes + ":" + day + ":" + month + ":" + year;
try {
final Date savedDate = sdf.parse(savedTimeValue);
final long savedTime = savedDate.getTime();
final long currentTime = System.currentTimeMillis();
final long rangeTimeMilliseconds = 1 * 60 * 1000; // 1 minute in milliseconds
if (currentTime > savedTime) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
if (currentTime > rangeTimeMilliseconds) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}catch(Exception e) {
e.printStackTrace();
}
}
I want develop TODO-List application with Realm Database, this application user can set Title, Date and time for Task/Todo .
I want when user set Date, hour save to database with 24h instead of am/pm.
for example : i want show hour this formatting 17:34 , but show me 05:34 !
I use this codes, but show me am/pm formatting.
Calendar method and save to database :
// Calendar Method
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, dialog_date.getDay()-1);
calender.set(Calendar.MONTH, dialog_date.getMonth()-1);
calender.set(Calendar.YEAR, dialog_date.getYear());
calender.set(Calendar.HOUR, dialog_date.getHour());
calender.set(Calendar.MINUTE, dialog_date.getMinute());
long now = System.currentTimeMillis();
Realm realm = Realm.getDefaultInstance();
Task_Provider task_provider = new Task_Provider(addTask, now, calender.getTimeInMillis(), false);
Code 1 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "hh:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
Code 2 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "kk:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
Code 3 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "HH:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
but this code not work for me!
How can save 24h in calendar method on Android? tnx all <3
I have two strings, the first one contains an actual date, and the second one contains a date format.
I want to compare both the strings. Here is my code:
for current date
Date referenceDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(referenceDate);
c.add(Calendar.MINUTE, -30);
//c.getTime();
//System.out.println("Date class"+c.getTime());
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateandTime = sdf.format(c.getTime());
System.out.println("Simple Date Format "+currentDateandTime);
and 2nd date code is here
private void setDate() {
try {
sbMain = obj.get("date_of_report").toString().split(" ");
} catch (JSONException e) {
}
String[] sb = sbMain[0].split("-");
String[] sb2 = sbMain[1].split(":");
System.out.println("Alert Time : " + sb[0] + " " + sb[1] + " " + sb[2] + " " + sb2[0] + ":" + sb2[1] + ":" + sb2[2]);
}
When you have all the components of your second date, e.g Day,time,Month and Year then use the same Calendar class to obtain date object by setting correct time and date components you retrieved, now you have two valid instances of your dates, get the values of both in Millis, and perform whatever comparision you want.