Hi Iam retrieving the events based on the datetime . When iam passing the datetime as query for getting events from google calender getting below exception.
private static void dateRangeQuery(CalendarService service) throws ServiceException,
IOException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Date dt = Calendar.getInstance().getTime();
//System.out.println(dateFormat.format(cal.getTime()));
// System.out.println(cal.getTime());
DateTime startTime = DateTime.parseDateTime(dateFormat.format(dt));
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.MINUTE, 20);
System.out.println(dateFormat.format(cal2.getTime()));
System.out.println(cal2.getTime());
DateTime endTime = DateTime.parseDate(dateFormat.format(cal2.getTime()));
CalendarQuery myQuery = new CalendarQuery(eventFeedUrl);
myQuery.setMinimumStartTime(startTime);
myQuery.setMaximumStartTime(endTime);
// Send the request and receive the response:
CalendarEventFeed resultFeed = service.query(myQuery,
CalendarEventFeed.class);
//System.out.println("Events from " + startTime.toString() + " to "
// + endTime.toString() + ":");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println();
}
Exception below:
Exception in thread "main" java.lang.NumberFormatException: Invalid date/time format.
at com.google.gdata.data.DateTime.parseDateTime(DateTime.java:303)
at GoogleCalender.dateRangeQuery(GoogleCalender.java:185)
at GoogleCalender.main(GoogleCalender.java:115)
please can anyone suggest how to resolve this issue
The XML dateTime pattern, expected by DateTime.parseDateTime(), is [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm].
So, the date should be formatted using the SimpleDateFormat yyyy-MM-dd'T'HH:mm:ss pattern (not tested).
But an even simpler way would be to simply use the DateTime constructor which takes a java.util.Date as argument, instead of transforming the Date to a String, and then thuis Date to a DateTime.
Related
I am trying to convert this DataTime object to Calendar object.
DateTime start = event.getStart().getDateTime();
DateTime format: 2015-11-11T19:25:55.000Z
I need format: "yyyy/MM/dd HH:mm:ss"
How can I cut TimeZone and convert it to Calendar object?
Original Google Calendar Api:
private List<String> getDataFromApi() throws IOException {
// List the next 10 events from the primary calendar.
DateTime now = new DateTime(System.currentTimeMillis());
List<String> eventStrings = new ArrayList<String>();
Events events = mService.events().list("primary")
.setMaxResults(10)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
// All-day events don't have start times, so just use
// the start date.
start = event.getStart().getDate();
}
eventStrings.add(String.format("%s (%s)", event.getSummary(),start));
}
return eventStrings;
}
You can use SimpleDateFormat to parse your 2015-11-11T19:25:55.000Z into an actual Date object. Once you've got that Date object, it's as easy as:
Calendar calendar = Calendar.getInstance();
calendar.setTime(your_date_object);
I hope this helps!
I'm trying do somthing with it, but its not work.
DateTime start = event.getStart().getDateTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String newDate = dateFormat.format(start);
Maybe someone know why i can't parse this data
DateTime start = event.getStart().getDateTime();
String NewDate = String.format("(%s)", start);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.getDefault());
cal.setTime(sdf.parse(NewDate));
All the time i have unparseable date exception.
I tried formats:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
yyyy-MM-dd'T'HH:mm:ssZZZZZ
yyyy-MM-dd'T'HH:mm:ss.SSSZZ
This work for me:
SimpleDateFormat dtExibicao = new SimpleDateFormat("dd/MM/yyyy");
Date dtInicio = new Date(event.getStart().getDateTime().getValue());
String stInicio = dtExibicao.format(dtInicio);
If you wanna a java.util.Calendar you can use a #k3v1n4ud3 sample code:
java.util.Calendar calendar = java.util.Calendar.getInstance();
calendar.setTime(dtInicio);
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}
I am getting a time from API like this "00:00" and I want to add Device GMT time to received time from API.
I am using following code for getting GMT Time of device
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.US);
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("dd:MM:yyyy HH:mm z");
String localTime = date.format(currentLocalTime);
Log.v("GMT time:", localTime + "");
Is there any inbuilt method to add GMT time to a specific time?
Maybe you can try something like this
public static void main(final String[] args) throws Exception {
Date date = new Date();
DateFormat localDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
DateFormat gmtDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
DateFormat nyDf = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
gmtDf.setTimeZone(TimeZone.getTimeZone("GMT"));
nyDf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("local : " + localDf.format(date));
System.out.println("GMT : " + gmtDf.format(date));
System.out.println("NY : " + nyDf.format(date));
}
You can try like this:
TimeZone gmtTime = TimeZone.getTimeZone("GMT+00");
date.setTimeZone(gmtTime);
String localTime = date.format(currentLocalTime);
Date and time conversion to some other Timezone in java
How can I verify if the calculated date is correct through selenium web driver?
Consider the following examples below:
From Date: 01/01/2001
Duration: 10
To Date: 01/10/2001
I will instruct selenium to input a date on from date field and duration.
The system shall automatically calculates the To date based on the inputted from date and duration.
I wonder if there's a way to verify if the calculated To Date is correct given that the inputted values on from date and duration fields may change time to time.
Static values for from date and duration fields is okay too - I guess.
Thanks!
You can do this using java.util methods. I assume you will be pass From Date and Duration as string to your selenium/webdriver from your test data set. You have to do following for each test data:
Calculate the To Date using util method (Code below for getToDate).
Get text in To Date using selenium/webdriver, for your test data.
Compare the text fetched by selenium/webdriver with the text returned by your getToDate method.
The method to get To Date:
public static String getToDate(String fromDate, String duration){
try {
String[] arrFromDate = fromDate.split("/");
int fromMonth = Integer.parseInt(arrFromDate[0])-1;
int fromDay = Integer.parseInt(arrFromDate[1]);
int fromYear = Integer.parseInt(arrFromDate[2]);
int intDuration = Integer.parseInt(duration);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, fromDay);
cal.set(Calendar.MONTH, fromMonth);
cal.set(Calendar.YEAR, fromYear);
cal.add(Calendar.DAY_OF_MONTH, intDuration);
String toDate = sdf.format(cal.getTime());
return toDate;
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
Code to verify:
String appToDate = driver.findElement(By.id("toDate")).getText();
String myToDate = getToDate("01/01/2001","10");
boolean isToDateCorrect = false;
if (appToDate.equals(myToDate )){
isToDateCorrect = true;
}
I suggest parsing the date instead of splitting the string
String strDate = "01/01/2001";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = simpleDateFormat.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 10); // 10 == duration
String outStr = simpleDateFormat.format(calendar.getTime());
Good Day.
I've got another problem related to Jtable.
I want to change the row color of a table if the date inside column (expiry) exceeds or is equal to the current date.
I tried this code but i get an error: java.lang.NumberFormatException: For input string: "2012-03-15"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
System.out.println(expDateString);
Double date = Double.parseDouble(expDateString);
Double val = Double.parseDouble(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(val >= date){
renderer.setBackground(red);
}
}
Thanks!
here's a new code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
Date today = new Date(expDateString);
System.out.println("ang churva is " + today);
Date given = new Date(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(today.compareTo(given)>=0){
renderer.setBackground(red);
}
}
but i get this exception: java.lang.IllegalArgumentException at Date today = new Date(expDateString);
Use the code
DATEDIFF('d',NOW(),exdate)
in your resultset query. It will return the difference. Alter it possibly to match your needs.
You can't cast a date string in a double
Double date = Double.parseDouble(expDateString); //does not work!
Simple example of how you can compare you dates. Note that if the objects in your JTable already are Dates, you don't need all the parsing, which would make your life easier.
The output of the code below is:
expiryDate=2012-03-15
tableDateOK=2012-03-12
tableDateExpired=2012-03-18
tableDateOK>expiryDate = false
tableDateExpired>expiryDate = true
Code:
public static void main(String args[]) throws ParseException {
String expiryDate = "2012-03-15";
String tableDateOk = "2012-03-12";
String tableDateExpired = "2012-03-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("expiryDate="+expiryDate);
System.out.println("tableDateOK="+tableDateOk);
System.out.println("tableDateExpired="+tableDateExpired);
System.out.println("tableDateOK>expiryDate = " + sdf.parse(tableDateOk).after(sdf.parse(expiryDate)));
System.out.println("tableDateExpired>expiryDate = " + sdf.parse(tableDateExpired).after(sdf.parse(expiryDate)));
}
line Double date = Double.parseDouble(expDateString);
this cannot work because string "2012-03-15" is simply not a valid double value.
I do not understand why you are trying to compare two double values:
if you have Date in table, use Date.after() and Date.before() to find out, whether your date is before or after now.
if you have String in table, use the SimpleDateFormat.parse() to get Date from it and do point 1
public String compareDate( Request request ) throws ParseException {
Date debitDate= request.getPaymentTxn().getCrValDt();
Date now = new Date();
String response="";
SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = sdfDate.format(now);
String strDebitDate = sdfDate.format(debitDate);
System.out.println("Current Date: " + strCurrDate);
Date currentDate = new SimpleDateFormat("dd/MM/yyyy").parse(strCurrDate);
Date txnDate = new SimpleDateFormat("dd/MM/yyyy").parse(strDebitDate);
System.out.println("C -> "+currentDate);
System.out.println("C -> "+txnDate);
if (txnDate!=null){
if (currentDate.equals(txnDate))
{
System.out.println("Valid Txn");
response="valid";
}
if (currentDate.after(txnDate))
{
System.out.println("--> Not Valid TXN Past");
response="notValid";
}
if (currentDate.before(txnDate)){
System.out.println("Future Valid TXn");
response="future";
}
}
return response;
}
PLease Chk it out its working fine