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
Related
In my scenario, I need to convert timestamp value to specific time format in react native. I tired below code but can't able to achieve exact formate output. How to achieve it?
var dateTime = new Date(23456789 * 1000);
this.setState({DateTime:('0' + dateTime.getUTCDate()).slice(-2) +
'/' + ('0' + dateTime.getUTCMonth()).slice(-2) +
'/' + dateTime.getUTCFullYear() +
'' + ('0' + dateTime.getUTCHours()).slice(-2)
});
Exact output expecting : Wed, 2/01/2000 - 1.10 AM
you can convert using the following
var timestemp = new Date( 23456789000 );
var formatted = timestemp.format("dd/mm/yyyy hh:MM:ss");
you can get day, date, year and month like this
var day = timestemp.getDay();
var date = timestemp.getDate();
var month = timestemp.getMonth() + 1;
var year = timestemp.getFullYear();
Update
var t = new Date(23456789000);
var formatted = ('0' + t.getDate()).slice(-2)
+ '/' + ('0' + t.getMonth()).slice(-2)
+ '/' + (t.getFullYear())
+ ' ' + ('0' + t.getHours()).slice(-2);
Output
29/08/1970 17
Update:
var t = new Date(1589343013000);
var hours = t.getHours();
var minutes = t.getMinutes();
var newformat = t.getHours() >= 12 ? 'PM' : 'AM';
// Find current hour in AM-PM Format
hours = hours % 12;
// To display "0" as "12"
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var formatted =
(t.toString().split(' ')[0])
+ ', ' +('0' + t.getDate()).slice(-2)
+ '/' + ('0' + (t.getMonth() + 1) ).slice(-2)
+ '/' + (t.getFullYear())
+ ' - ' + ('0' + t.getHours()).slice(-2)
+ ':' + ('0' + t.getMinutes()).slice(-2)
+ ' ' + newformat;
Output :
Wed, 13/05/2020 - 09:40 AM
I tried this {${new Date(23456789000).toLocaleDateString('en-GB')}}, got 29/09/1970 in output.
Instead of timestamp, I used my date value fetched from database e.g. {${new Date(myobject.myfield).toLocaleDateString('en-GB')}} that also worked, I've defined inteface in React that matches my db object.
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();
}
}
I'm trying to convert the calendar which i set the time milliseconds from 1 1 1970 as below:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(1417780800);
Although when I'm trying to convert this calendar to a string as in this format "yyyy-MM-dd HH:mm:ss" it always set the date as 1970-1-17 9:49:40 when it should be 2014-12-1 12:00:00
I used this way to convert the date:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format.format(c.getTime());
Also, using this way is getting wrong:
String date = "" + c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
Any idea why?
Thanks in advance.
You can try something like...
DateFormat.getDateInstance().format(1417780800);
It will return Date in String format.
Jan 17, 1970
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.
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;
}