I am accessing Dot net web services and using Ksoap library as my web services are Soap based.
Basically i want to save the dates and show them in list at it is. I do not want the date conversion to any specific region or time zone.
my dates which are coming from services has following pattern please have an example of threee different fields.
patient DOB = 1974-05-18T00:00:00
Collection Date = 2016-07-27T11:00:00
attachment Date uploaded = 2016-09-28T10:19:23.48
and I am using following method to convert them
public static Date convertStringToDate(String date,String dateFormat)throws Exception {
Date output = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
output = simpleDateFormat.parse(date);
} catch (ParseException e) {
throw e;
}
return output;
}
where dateFormat is "yyyy-MM-dd" and whereas date could be any string shown above in above example.
Problems:
1> When I convert date using that method I sometimes get accurate time and date
2> Some times I observed slightly changed in time , like 2 to 7 hours shift in time. this is due to time zone conversion
3> Some times I observe a whol day shift. Let suppose if the date that was coming from server was 2016-09-28T10:19:23.48 after conversion it becomes 2016-09-27 to me .
Whats wrong ? How can I simple show date as it is from web services How can i get that except saving dates directly in strings and showing those strings by splitting.
Please help me.
Update
i am converting back my date object back to string to show on UI in following manner
public static String convertDateToString(Date date,String dateFormat)throws Exception {
String output = "";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
output = simpleDateFormat.format(date);
} catch (Exception e) {
throw e;
}
return output;
}
To achieve that, you need to know the actual timezone and dateformat of the server. If you knew it already, the following snippet would be useful
public static String parseDateFormat(String incomingDate, String inputFormat, String outputFormat) {
String finalDate = null;
SimpleDateFormat input = new SimpleDateFormat(inputFormat); // server date format
input.setTimeZone(TimeZone.getTimeZone(SERVER_TIMEZONE)); // timezone set in the server
SimpleDateFormat output = new SimpleDateFormat(outputFormat); // format to which you want to convert
output.setTimeZone(Constants.UTC_TIMEZONE); // timezone to which you want to convert
try {
Date realDate = input.parse(incomingDate);
finalDate = output.format(realDate);
} catch (ParseException e) {
Log.e("Error", e.getMessage(),e);
}
return finalDate;
}
Setting the time zone on the date format adds an offset to the time stamp. And your server's time format doesn't include any time zone.
Remove the line simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
You generally need to set the time zone only when you intend to account for the difference between locales.
Related
I'm trying to see how I can compare if the new date is after the old date if so no data will be shown from the firebase database. I am having trouble with this because my app crashes when I test it I believe I'm doing something wrong. Can someone help me with this issues? Below is my code. Thanks in advance
//Code
if(dataSnapshot.exists()){
//progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
UserInformation2 upload=postsnapshot.getValue(UserInformation2.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M-dd-yyyy");
//String now = simpleDateFormat.format(new Date());
Date d=new Date();
String AdCreationDate = postsnapshot.child("created").getValue(String.class);
//SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd")
try {
Date new_date = simpleDateFormat.parse(String.valueOf(d));
Date old_date = simpleDateFormat.parse(AdCreationDate);
if(new_date.after(old_date)){
// Your time expired do your logic here.
Toast.makeText(getContext(), "Your data expired", Toast.LENGTH_SHORT).show();
}else{
myUploads.add(upload);
recyclerView.invalidate();
}
} catch (ParseException e) {
e.printStackTrace();
}
//simpleDateFormat.format(d);
//Date e=new Date(old);
}
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
Stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.tout, PID: 22667
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:638)
Your error isn't in the comparison, it's in the String old = simpleDateFormat.format(new Date(Date.parse(AdCreationDate)));
Check the value of AdCreationDate it might not be compatible with a list of valid date formats that can be parsed, at the very least you can place AdCreationDate into a SimpleDateFormat and then parse that.
You need to change this logic. When working with dates it's always better to work with timestamp. This is easy to convert to date or anything else and also easy to compare between dates.
So, when you are saving your date to the database just save it as
long timestamp = date.getTime(); //this will return time in milliseconds
Then when you retreive the values from database, you don't even have to format them before checking which one is older. You can simply use this:
long database_timestamp = postsnapshot.child("created").getValue();
long current_timestamp = System.currentTimeMillis();
if (current_timestamp > database_timestamp) //this will check if current_timestamp has greater value then database_timestamp, if it has it means that it's date from later in time
Now you can simply convert that to date and use SimpleDateFormat to format it as you want:
Date new_date = new Date(current_timestamp);
SimpleDateFormat format = new SimpleDateFormaT("MM-dd-yyyy");
This also covers each hour, second, minut,e or anything else you need. So, this will also check if the current date is greater than the other one even if there is only a few seconds difference between them. Which means your data will be live. If you don't need this you can also avoid it by setting the hour, minutes, and seconds on the Date to 0.
It looks like the error is actually related to
Date new_date = simpleDateFormat.parse(String.valueOf(d));
If you comment out that line and then update the if statement to
if(d.after(old_date)){
You don't need to parse the new date as it's already a Date object. You only need to parse the date from your snapshot as it is a string.
I'd also change the new date variable d to something more meaningful as it well help the readability of the code and the Java standard for naming variables is to use camel case where the scond word is capitalised without an underscore i.e. 'oldDate'. It's good to get into the habit of following these conventions.
I am trying to grab a range of dates from a calendar picker view and then put them into a string list to eventually be put into firebase firestore. I've been at this for some time but cannot get past the "parse" part of it. I've searched stackO and found most answers only pertain to a single date string as shown here which I have gotten to work. I'm just having issues with a list of dates.
this is what I have so far:
CalendarPickerView bookProfileCalendar;
DateFormat dateRangeInputFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
SimpleDateFormat dateRangeOutputFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
List<Date> testListDate = bookProfileCalendar.getSelectedDates();
for (Date x: testListDate){
String selectedDatesFormatted = dateRangeInputFormat.format(x); //this allows the input to be read as a date in its default format
String test = String.valueOf(selectedDatesFormatted); //not sure this is necessary
// Date test2 = dateRangeInputFormat.parse(test); // <-- this gives me parse underlined red saying "unhandled exception: java.text.ParseException
Log.d(TAG, "onClick: testList dates: " + test);
}
any help or guidance is appreciated.
It turns out I just needed some sleep...and to also surround the parse part in a try/catch block. IDK why I wasn't seeing that last night. Anyhow, this is what I ended up with
List<Date> testListDate = bookProfileCalendar.getSelectedDates();
for (Date x: testListDate){ // preferred way of doing for loops now!!!
String selectedDatesFormatted = dateRangeInputFormat.format(x);
String test = String.valueOf(selectedDatesFormatted);
try {
Date test2 = dateRangeInputFormat.parse(test);
String test3 = dateRangeOutputFormat2.format(test2);
Log.d(TAG, "onClick: test3: " + test3);
} catch (ParseException e) {
e.printStackTrace();
}
``
Im trying to parse date of type 23-May-2016 and 24-May 2016 for instance..
Following code demonstrates how im parsing the date.
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
Date validityDate = null;
Date nextDueDate = null;
try {
validityDate = format1.parse(mValidityDate.getText().toString());
nextDueDate = format1.parse(mNextDueDate.getText().toString());
int validate = validate(validityDate, nextDueDate);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(),Toast.LENGTH_SHORT).show();
}
Following is the code that finds the number of difference between two dates.
public static int validate(Date valid, Date nextDueDate) {
return (int) ((nextDueDate.getTime() - valid.getTime()) / (1000 * 60 * 60 * 24l));
}
The problem is that, im getting Date parser error at offset 3. Why is that so?
You need to use two different SimpleDateFormat
For date 23-May-2016 you need new SimpleDateFormat("dd-MMM-yyyy");
For date 24-May 2016 you need new SimpleDateFormat("dd-MMM yyyy");
You are using the pattern "dd-MM-yyyy" which means you're trying to parse a date of the form 12-05-2016.
If you need to parse a date such as "12-May-2016", then you have to use 3M letters for the month as follows. "dd-MMM-yyyy".
However, this will output "12-Jun-2016", if you parse the date "12-06-2016".
If you need the complete month, then you should use 4M letters. E.g: "dd-MMMM-yyyy". Then it will output 12-June-2016.
I am using openweather API for calling current location.In JSON parsing, I saw "dt": 1457852143 (UTC/unix) http://openweathermap.org/weather-data which means last updated.So in my app, I stored that value in String variable String last_update=total.getString("dt") where total holding the full JSON data.I ran my app and got the output as 1457852143 on screen.Although I wanted it to show in local time but I am unable to convert.
I am using Android Studio 1.5.Any suggestion would be highly appreciated.
I've used the following before to do this. This is using the Date class but I've heard it's better to use the Calendar class. This should get you in the right direction though.
public static String convertUTCtoLocalTime(String p_city, String p_UTCDateTime) throws Exception{
String lv_dateFormateInLocalTimeZone="";//Will hold the final converted date
Datelv_localDate = null;
Stringlv_localTimeZone ="";
SimpleDateFormat lv_formatter;
SimpleDateFormat lv_parser;
//Temp for testing(mapping of cities and timezones will eventually be in a properties file
if(p_city.equals("LON")){
lv_localTimeZone="Europe/London";
}else if(p_city.equals("NBI")){
lv_localTimeZone="EAT";
}else if(p_city.equals("BRS")){
lv_localTimeZone="Europe/Brussels";
}else if(p_city.equals("MNT")){
lv_localTimeZone="America/Montreal";
}else if(p_city.equals("LAS")){
lv_localTimeZone="PST";}
//create a new Date object using the UTC timezone
lv_parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
lv_parser.setTimeZone(TimeZone.getTimeZone("UTC"));
lv_localDate = lv_parser.parse(p_UTCDateTime);
//Set output format - // prints "2007/10/25 18:35:07 EDT(-0400)"
lv_formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z'('Z')'");
System.out.println("convertUTCtoLocalTime "+p_city+": "+ "The Date in the UTC time zone(UTC) " + lv_formatter.format(lv_localDate));
//Convert the UTC date to Local timezone
lv_formatter.setTimeZone(TimeZone.getTimeZone(lv_localTimeZone));
lv_dateFormateInLocalTimeZone = lv_formatter.format(lv_localDate);
System.out.println("convertUTCtoLocalTime: "+p_city+": "+"The Date in the LocalTime Zone time zone " + lv_formatter.format(lv_localDate));
return lv_dateFormateInLocalTimeZone;
}
Im trying to display the current time in a format like 7:45pm instead of 19:45 but i can't seem to find the right format option.
Time cTime= new Time(Time.getCurrentTimezone());
cTime.setToNow();
clock.setText(cTime.format("%H:%M"));
This seems to display military
You're using Time.format(), so you can refer to the C++ strftime documentation for formatting rules. Your format string should be %I:%M%P for 12-hour time.
Use SimpleDateFormat with a - meaning am/pm marker.
Example:
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("h:mmaa");
try {
String now = dateFormat.format(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}