Converting Timestamp as String to Date in android - android

I am getting Timestamp value as 1291204449 from server so I extracted the value by
implementing handler.
Now I want to convert timestamp value to date.(But the problem is in my activity I stored this value in a string variable because handler returning in string format).

Just use the Time class. Try something similar to this.
Time time = new Time();
time.set(Long.valueOf(yourTimeString));
If you really need a Date object just try this.
Date date = new Date(Long.parse(yourTimeString));

I have a function for converting timestamps in String Format:
public static String create_datestring(String timestring){
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(timestring));
timestring = add_string(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)),"0",2,0) + "." + add_string(String.valueOf(cal.get(Calendar.MONTH)+1),"0",2,0) + "." + String.valueOf(cal.get(Calendar.YEAR)) + " " + add_string(String.valueOf(cal.get(Calendar.HOUR_OF_DAY)),"0",2,0) + ":" + add_string(String.valueOf(cal.get(Calendar.MINUTE)),"0",2,0);
return timestring;
}

Related

JodaTime not working

I an new to android and am having trouble working with jodatime. I am getting the same error as many people on here and I have tried all the suggestions but nothing is working for me. I am trying to display the variables a user selected from a date and time picker e.g. 'dayNow, monthNow' etc into one combined variable called 'timeselected' and set it to a textbox so then I can carry out a calculation in jodatime further on down.
The code is as follows:
DateTime dateTime = new DateTime(timeselected);
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MM yyyy" + "\n" + " h:mm a ");
String formattedtime = fmt.print(dateTime);
CalculateButton.setText(formattedtime);
// Plus some hours, minutes, and seconds to the original DateTime.
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("dd MM yyyy" + "\n" + " h:mm a ");
DateTime dateTime1 = dateTime.plusHours(timeadded);
String endtimecalc = fmt2.print(dateTime1);
TextView endtime = (TextView) findViewById(endtimetextView);
endtime.setVisibility(View.VISIBLE);
endtime.setText(endtimecalc);
String timeselected = dayNow + "-" + monthNow + "-" + yearNow + " " + hourNow + ":" + minuteNow;
DateTime datetimselected = DateTime.parse(timeselected);
usertimeselection.setText((CharSequence) datetimselected.toDate());
}
});
FATAL EXCEPTION: main
Process: com.almac.tracker, PID: 29114
java.lang.IllegalArgumentException: Invalid format: "2017-11-23 T 4:56" is malformed at " T 4:56"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
at org.joda.time.DateTime.parse(DateTime.java:160)
at org.joda.time.DateTime.parse(DateTime.java:149)
at com.almac.tracker.CreateLine$5.onClick(CreateLine.java:274)
at android.view.View.performClick(View.java:6219)
at android.view.View$PerformClick.run(View.java:24482)
at android.os.Handler.handleCallback(Handler.java:769)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
From DateTime.parse(String str) documentation:
Parses a DateTime from the specified string.
This uses ISODateTimeFormat.dateTimeParser().
Your datetime string is not valid for the ISODateTimeFormat, it does not accept / but -.
So either change your / to - and comply to the rule:
date-opt-time = date-element ['T' [time-element] [offset]] (see that 'T' between the date and time elements!)
So your datetime string should be like this:
String timeselected = yearNow + "-" + monthNow + "-" + dayNow + "'T'" + hourNow + ":" + minuteNow;
DateTime datetimselected = DateTime.parse(timeselected);
either use your own formatter via the DateTime.parse(String str, DateTimeFormatter formatter) method.
UPDATE 1
After running some tests indeed the 'T' is not accepted by the default parser. A string that passes from the parser is :
"2017-11-23T04:56"
So make sure no spaces exist between the date section, the "T" character and the time section.
String timeselected = yearNow + "-" + monthNow + "-" + dayNow + "T" + hourNow + ":" + minuteNow;
UPDATE 2
Attaching my test code for the parser
public class Main {
public static void main(String[] args) {
String timeselected = "2017-11-23T04:56";
DateTime datetimselected = DateTime.parse(timeselected);
System.out.println(datetimselected.toDate());
}
}
output:
Thu Nov 23 04:56:00 EET 2017

Convert Received date time to local timezone time Android

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();
}
}

How to set 24h in Calendar method on Android?

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

Joda DateTime object adding +1 hour

i have the following code:
Log.e(TAG, "startTime = " + startTime);
DateTime dateTimeStart = new DateTime(startTime);
Log.e(TAG, "dateTimeStart = " + dateTimeStart );
.
which when logged out produces the following:
startTime = 2014-10-30T12:00:00+00:00
dateTimeStart = 2014-10-30T13:00:00.000+01:00
.
Why is an extra hour getting added on to the original time?
edit
How can i remove the +1:00, i haven't specified that.
Thanks
DateTime is an object consisting of a date, a time, and a timezone. In your case, you took startTime and converted it into an equivalent DateTime using the default system timezone.
+01:00 means "this timestamp is in some UTC+1 timezone", so 12:00:00.000+00:00 means the same as 13:00:00.000+01:00
So your timestamp was created at 12:00 British time = 13:00 Central European time.
If you want the time in UTC, do
DateTime dateTimeStart = new DateTime(startTime, DateTimeZone.UTC);
Use split method.
String splitDateTime[]=dateTimeStart.split("\\+");
dateTimeStart=splitDateTime[0];
Default DateTime::toString() method returns date in format yyyy-MM-ddTHH:mm:ss.SSSZZ .
+01:00 and +00:00 are the timezone offsets (ZZ in date format).
So if you want to print date without timezone offset, you should use another format. E.g. with method DateTime::toString(String):
String dtFormat = "yyyy-MM-dd'T'HH:mm:ss";
Log.e(TAG, "startTime = " + startTime.toString(dtFormat));
...
Log.e(TAG, "dateTimeStart = " + dateTimeStart.toString(dtFormat ));

Compare Date String in Android

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.

Categories

Resources