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();
}
``
Related
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.
So Im trying to print the string "Eastern Daylight Time" instead of EDT . This should be dynamic and not hardcoded. Looking into DateFormatter class did not lead me to an answer that worked.
Here was an example that allows me to format but did not lead me to my specific answer.
I am getting the date back in the following format -
2013-06-08T00:00:00-04:00
Here are somethings that I have tried -
1)
String dateString = changeFormatDateStringWithDefaultTimeZone(paymentConfirmation.getTransactionDate(),
"yyyy-MM-dd'T'HH:mm:ssZ",
"M/d/yyyy hh:mm a zz");
public static String changeFormatDateStringWithDefaultTimeZone(String value, String ip_format, String op_format) {
if (value == null)
return null;
try {
SimpleDateFormat opSDF = new SimpleDateFormat(op_format, Locale.US);
opSDF.setTimeZone(TimeZone.getDefault());
SimpleDateFormat inSDF = new SimpleDateFormat(ip_format, Locale.US);
Date date = inSDF.parse(value);
return(opSDF.format(date));
} catch (Exception e) {
Log.e("Err", "Failed to convert time "+value);
e.printStackTrace();
}
return null;
}
2)
Date today = Calendar.getInstance().getTime();
String todayString = DateUtils.convertDateToStringWithTimeZone(today);
public static String convertDateToStringWithTimeZone(Date date){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = df.format(date);
dateString += " " + TimeZone.getDefault().getDisplayName(false, TimeZone.LONG);
return dateString;
}
These always print timezone as EDT and I want the string Eastern Daylight Time. Can anyone help me out with this?
Okay, based on your last edit of the question, the solution should be like this:
case 1)
The output pattern should be changed to "M/d/yyyy hh:mm a zzzz" (note the count of z-symbols to enforce the full zone name). Depending on the date and the underlying timezone, the formatter SimpleDateFormat will automatically determine if the daylight or the standard name is to be used.
case 2)
Use TimeZone.getDefault().getDisplayName(true, TimeZone.LONG) to enforce the long daylight name. If your default timezone is "America/New_York" then such an expression should print "Eastern Daylight Time". Note that the boolean parameter has been changed to true.
I'm learning Android a simple screen with user Information like name,Date of Birth and so on.
All are Text View and Edit Text.
In my pojo Date of Birth datatype is String.
When I enter date and try to get the date it is showing as some long number I this it is date and time in milliseconds.
Can any one help me to solve this.
If i understand your problem.. Try this...
Date d1 = new Date();
d1.setTime(time_in_milliseconds);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
And then you can get day,month, year..
int number_of_day = cal.get(Calendar.DAY_OF_MONTH)
Check this :
public Date getDateByFormat(String time, String format) {
if (time == null || "".equals(time)) return null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
return sdf.parse(time);
} catch (ParseException e) {
Log.d(Constants.TAG, "Could not parse date: " + time + " Due to: " + e.getMessage());
}
return null;
}
here format is your date string format. Like "yyyy-MM-dd HH:mm:ss"
User will input a date and he/she will input days to add to it.
Like this:
Date: 1/1/2015
Days to add: 20
The output should be 1/21/2015
I am wondering how to do that. I am beginner in android. T__T cries I tried other sources but i don't understand them at all. THANKS
THE USER WILL SUPPLY THE DATE TO ADD AND THE NUMBER OF DAYS TO ADD. All other sources only explain adding the current date with the number of days.
You need to parse the string to a date first.
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy");
try {
Date myDate = dateParser.parse("01/01/2015");
Calendar c = Calendar.getInstance();
c.setTime(myDate);
c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 20);
Date newDate = c.getTime();
String newFormattedDate = dateParser.format(newDate);//01/21/2015
} catch (ParseException e) {
e.printStackTrace();
//handle exception
}
I want to convert date time object in java to json string in format as below:
{"date":"/Date(18000000+0000)/"}
I did like this but it didn't give me the format i desired:
JSONObject object = new JSONObject();
object.put("date",new Date());
and the result of object.toString()
{"date":"Fri May 04 11:22:32 GMT+07:00 2012"}
i want the string "Fri May 04 11:22:32 GMT+07:00 2012" transform to "/Date(18000000+0000)/" (18000000+0000 here is just a example).
Thanks for your help.
Here is my solution, although it is not a good way, but I finally find a workable solution.
SimpleDateFormat format = new SimpleDateFormat("Z");
Date date = new Date();
JSONObject object = new JSONObject();
object.put("date", "/Date(" + String.valueOf(date.getTime()) + format.format(date) + ")/");
public static String convertToJsonDateTime(String javaDate)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date currentDate = null;
try {
currentDate = dateFormat.parse(javaDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long time =currentDate.getTime();
return "\\/Date("+time+"+0000)\\/";
}
My solution : I think this is the simplest Way
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
yourJsonObject.accumulate("yourDateVarible",dateFormat.format(new Date()));
The date format that you want is /Date(<epoch time><Time Zone>)/.
You can get the epoch time in java using long epoch = System.currentTimeMillis()/1000;(found at this link) and the time zone you can get by using the date and time patteren as Z. Then combine all the strings into one and store it to the Json Object.
Other possibility is that the time you are getting from iOS device may be of the pattern yyMMddHHmmssZ as got from here. Check the output on the iOS device at different times and identify the correct pattern.
From json.org's description of JSONObject:
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
This library doesn't support the "complex" mapping of a Date to a JSON representation. You'll have to do it yourself. You may find something like SimpleDateFormat helpful.
If your format like this -> "DDmmYYYY+HHMM"
DD -> Day (2 Digit)
mm -> Month (2 Digit)
YYYY -> Year (4 Digit)
HH -> Hour
MM -> Minute
Than you can do like this:
SimpleDateFormat format = new SimpleDateFormat("DDmmYYYY+HHMM");
JSONObject object = new JSONObject();
object.put("date", "/Date(" + format.format(new Date()) + ")/");
I suppose that's a representation of ISO international date-time format.
YYYYMMDD+HHMM
I think now you will be able to create that string
may be like,
Date d=new Date();
String tmp="";
tmp="/Date("d.getYear()+""+d.getMonth()+""+d.getDate()+"+"+d.getHours()+""+d.getMinutes()+")/";
Upgrade one of the previous answer:
public static String convertToJsonDateTime(Date dateToConvert) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
long time = dateToConvert.getTime();
return "/Date(" + time + "+0000)/";
}