Convert ISO date string to Timestamp [duplicate] - java

This question already has answers here:
How to get start and end range from list of timestamps?
(2 answers)
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
How to parse "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" date format to simple in Android? [duplicate]
(3 answers)
Closed 4 years ago.
String startDate = "2018-07-29T09:50:49+05:30";
String TAG = "Extra";
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMATE);
try {
Date date = df.parse(startDate);
System.out.println(TAG + "Start: " + date.getTime());
System.out.println(TAG + "Start: " + date.getDate());
System.out.println(TAG + "Start: " + date.getHours() + ":" + date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Its giving an error java.text.ParseException: Unparseable date: "2018-07-29T09:50:49+05:30"
Any idea what I am missing here?

The new API turns out to be even easier in this case. Your pattern is the default format for java.time.ZonedDateTime:
ZonedDateTime date = ZonedDateTime.parse("2018-07-29T09:50:49+05:30")

You can try something like this
String time="2018-07-29T09:50:49+05:30";
ZonedDateTime date = ZonedDateTime.parse(time);
System.out.println(date);
String TAG = "Extra";
System.out.println(TAG + "Start: " + date.getDayOfMonth());
System.out.println(TAG + "Start: " + date.toLocalDateTime());
System.out.println(TAG + "Start: " + date.getHour() + ":" + date.getMinute()) ;

You can use this method to get the date and time for your date:
Below are the different formats of dates, you can use your own and pass it to the method as params.
public String localFormat = "yyyy-MM-dd HH:mm";
public String alarmFormat = "yyyy-MM-dd-HH-mm";
public String defaultFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public String calendarFormat = "yyyy-M-d";
public String calendarFormatCh = "yyyy-M-dd";
public String calendarFormatRc = "yyyy-MM-dd";
public String reminderFormat = "dd/MM/yyyy hh:mm a";
public String getFormattedDate(Context mcontext, String date, String currFormat, String RequireFormat) {
Utils.e(Tag + "750", currFormat + "date " + date);
SimpleDateFormat sdf = new SimpleDateFormat(currFormat);
SimpleDateFormat sdfReq = new SimpleDateFormat(RequireFormat);
long time = 0;
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
time = sdf.parse(date).getTime();
return sdfReq.format(time).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Just pass the date in the current format and in the format that you are expecting, it will return you accordingly. If you want time only, you can get using this method, you will need to implement it as per your requirement.

The Format you are using to parse has miliseconds too
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
You need to change that to
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.XXX";
I tried below example and it worked:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
String startDate="2018-07-29T09:50:49+05:30";
String TAG = "Extra";
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ssXXX" ;
DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMATE);
try {
Date date = df.parse(startDate);
System.out.println(TAG + "Start: " + date.getTime());
System.out.println(TAG + "Start: " + date.getDate());
System.out.println(TAG + "Start: " + date.getHours() + ":" + date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
ExtraStart: 1532838049000
ExtraStart: 29
ExtraStart: 9:1532838049000

Related

Convert a String of 6 into mm/dd/yyyy h:m with conditions

I'm developing an API in which one of the object should satisfy the below:
I've a column in Postgress DB as :
input = 201800
Input(column -datatype is character[6]) 201801
.
.
.
201812
Requirement :
Check if the input is current year
check if the last 2 digits are zeros , then ignore
if it is 201802 : dd=01(always), 02(Month) and 2018(year)
after checking the conditions, if it satisfies display like this :
For Ex: input = 201803 then o/p should in MM/DD/YYYY h:m format
Always month is 01 for month in between (01-12),O/P = 01/03/2018 12:00
I tried this, but didn't gibe O/P as per ,y requirement:
public class sample {
public static void main(String[] args) {
try {
String input= "201700" + "00";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
Date d = sdf1.parse(input);
System.out.print(d);
String formateDate = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(d);
System.out.print(formateDate);
} catch(Exception e) {}
}
}
Appreciate your help!
I created a method mapDate() that is actually verifying your condition and return the wanted output. You just have to pass the value as parameter to the method. See the example below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
String result1 = mapDate("201802"+"00");
System.out.print("result: " + result1 + "\n");
String result2 = mapDate("201702"+"02");
System.out.print("result: " + result2 + "\n");
String result3 = mapDate("201802"+"02");
System.out.print("result: " + result3);
}
public static String mapDate(String value){
String myDate;
myDate = "";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
String thisYear = format1.format(new Date());
if(!value.substring(value.length() - 2).equals("00") && value.substring(0, 4).equals(thisYear))
myDate = "01/" + value.substring(4, 6) + "/" + value.substring(0, 4) + " 12:00";
return myDate;
}
}
The ouput of this example is:
result:
result:
result: 01/02/2018 12:00

I need to show time 24 hrs format to 12 (am/pm) hrs format [duplicate]

This question already has answers here:
Display current time in 12 hour format with AM/PM
(15 answers)
Closed 4 years ago.
In this code show wrong time in case of 12:01:00 it shows 12:00 AM but right time is 12:00 PM:
private static final String sourceFormat = "hh:mm:ss";
private static final String targetFormat = "hh:mm a";
public static String convertTimeFormat(String dateStr) {
if (dateStr.equals("")) {
return "";
}
Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
SimpleDateFormat form = new SimpleDateFormat(sourceFormat);
Date date = null;
try {
date = form.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat);
String newDateStr = postFormater.format(date);
Log.d("Lead Response", newDateStr);
return newDateStr;
}
Thank you very much for your time and assistance in this matter.
private static final String sourceFormat = "hh:mm:ss";
change to
private static final String sourceFormat = "HH:mm:ss";
It's working I checked in My IDE
private static final String sourceFormat = "HH:mm:ss";
private static final String targetFormat = "hh:mm a";
public static String convertTimeFormat(String dateStr) {
if (dateStr.equals("")) {
return "";
}
Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
**SimpleDateFormat form = new SimpleDateFormat(sourceFormat, Locale.US);**
Date date = null;
try {
date = form.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat, Locale.US);**
String newDateStr = postFormater.format(date);
Log.d("Lead Response", newDateStr);
return newDateStr;
}

Operator '<' cannot be applied to 'java.lang.String'

i got the system time in a string for example something like "1240".
then i wanted to do something like if the system time was < than 1240,then close the application.
but it gives me the "Operator '<' cannot be applied to java.lang.String!" Error!
My code is :
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.showtime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int mynum = 1240;
String curTime = hours + "" + minutes;
txtCurrentTime.setText(curTime);
if(curTime < mynum ){
System.exit(0);
}
}catch (Exception e) {}
}
});
What's the problem?
try{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String str1 = String.valueOf(hours1) + ":" + String.valueOf(minutes1) + ":" + "00";
String str2 = String.valueOf(hours2) + ":" + String.valueOf(minutes2) + ":" + "00";
Date date1 = formatter.parse(str1);
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
// if date2 > date1
}
}catch (ParseException e1){
e1.printStackTrace();
}
formats for dates
check date/time format as per your requirement from here
< is not defined for a string and an int of course . So you can't use it .
your current time can be calculated like this :
int curTime = 100*hours + minutes;
then you can use < between two integers.
I believe though you must use System Milliseconds which is more usual.
if(hours * 100 + minutes < mynum){
System.exit(0);
}

How to Disable date ranges in java calendar

In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.

Gettin date from a SMS message android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android - get date time from SMS timestamp in miliseconds
I am using the following code to record sms messages:
public void getColumnData(Cursor cur, Context context) {
ArrayList<String> exportBuffer = new ArrayList<String>();
try {
if (cur.moveToFirst()) {
String id;
String date;
String phoneNumber;
String body;
int idColumn = cur.getColumnIndex("_id");
int dateColumn = cur.getColumnIndex("date");
int numberColumn = cur.getColumnIndex("address");
int bodyColumn = cur.getColumnIndex("body");
do {
id = cur.getString(idColumn);
date = cur.getString(dateColumn);
body = cur.getString(bodyColumn);
phoneNumber = cur.getString(numberColumn);
String FormattedDate;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
FormattedDate = sdf.format(date).toString();
exportBuffer.add(id + " ," + FormattedDate + " ," + body + " ,"
+ phoneNumber);
} while (cur.moveToNext());
}
WriteToFile(exportBuffer,context);
} catch (Exception e) {
int MessageDuration = Toast.LENGTH_SHORT;
CharSequence text = "An Error Occurred, Code:104";
Toast toast = Toast.makeText(context, text, MessageDuration);
toast.show();
}
}
It all works fine apart from the date string I have no idea what format it is in which means I can't format it to a correct date here is an example of one of the dates:
1309817682651
Thanks in advance.
Try using this piece of code:
public static String millisToDate(long currentTime) {
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
finalDate = date.toString();
return finalDate;
}

Categories