Set date of calendar - java

Ok, so what I'm trying to do is to set the set the date of a calendar instance, and then return the week_of_year. I am doing so by using the Calendar.set() functio
public String weekInYearForm = "ww";
SimpleDateFormat formWIM = new SimpleDateFormat(weekInYearForm, Locale.US);
Calendar lc = Calendar.getInstance();
lc.set(Calendar.YEAR, lYear);
lc.set(Calendar.MONTH, lMonth);
lc.set(Calendar.DAY_OF_MONTH, lDay);
wiy = formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
To get the lYear, lMonth, and lDay values, I am passing a string in the format 04/26/2013 to through the following steps:
String[] arrDate = dateIn.split("/");
int lMonth = Integer.parseInt(arrDate[0]) - 1;
Log.d("SaveHandler", "Month is: " + lMonth);
int lDay = Integer.parseInt(arrDate[1]);
Log.d("SaveHandler", "Day is: " + lDay);
int lYear = Integer.parseInt(arrDate[2]);
Log.d("SaveHandler", "Year is: " + lYear);
The problem I am facing is that when I look at what is outputed to wiy, it is always 1. Upon some further debugging, I realized that the time is being left at epoch time, and not setting to the values I need.
I also tried using lc.set(lYear, lMonth, lDay), also to no avail. If anyone has any ideas, I would greatly appreciate them.
*EDIT: I did some debugging earlier and it is returning 1970 for the year and 0 for the month.

use
formWIM.format(lc.getTime());
instead of
formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
EDIT
You can parse your date (instead of dateIn.split( etc.)
SimpleDateFormat monthDayYear = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //04/26/2013
Date date = monthDayYear.parse("04/26/2013");
and then format it
SimpleDateFormat formWIM = new SimpleDateFormat("ww", Locale.US);
formWIM.format(date);

This code is correct, the problem is in formWIM.format(...) or the battery of your motherboard clock is drained.

Related

Date selector based on months in Java

I have code in Java for Selenium Webdriver TestNG. Is for comparing if the date on the website is same as today date.
Problem is that date on webpage dateOnWebpage for 11th April 2018 is in format
Today 4/11/2018
So I made selecter to compare date formats if months < 10 if(javaDateSelector < 10) than date to compare is in format M/dd/yyyy else is in format MM/dd/yyyy.
Is there better way to code it than I made it? Because I needed to parse date to string and than to int to compare it and code is quite long.
#Test(priority=3)
public void test3DateCheck() throws Exception
{
String dateOnWebpage = driver.findElement(By.xpath("//div[#id='homeCalendarSection']/div/div[2]/table/tbody/tr/td/div/ul/li")).getText();
System.out.println("Today Date on webpage is : " + dateOnWebpage);
//DateFormat dateFormat1 = new SimpleDateFormat("M/dd/yyyy");
DateFormat dateFormat1 = new SimpleDateFormat("MM");
Date date = new Date();
String javaDate1 = dateFormat1.format(date);
int javaDateSelector = Integer.parseInt(javaDate1);
if(javaDateSelector < 10)
{
DateFormat dateFormat2 = new SimpleDateFormat("M/dd/yyyy");
String javaDate2 = dateFormat2.format(date);
System.out.println("Today Date from Java is : " + javaDate2);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate2);
}
else
{
DateFormat dateFormat3 = new SimpleDateFormat("MM/dd/yyyy");
String javaDate3 = dateFormat3.format(date);
System.out.println("Today Date from Java is : " + javaDate3);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate3);
}
}
If you don’t care whether the date on the web page is written with leading zero for month and day of month or not and just want to test whether the date is correct:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("'Today' M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
System.out.println("Today is " + today);
LocalDate observedDate = LocalDate.parse(dateOnWebpage, dateFormatter);
Assert.assertEquals(today, observedDate);
Rather than testing the string I am parsing the date and testing it. Even though the pattern has one M and one d in it, parsing two-digit months and two-digits day of month poses no problem.
If on the other hand you also want to test that the date on the web page is written without any leading zeroes, it’s best to test the string, like you already did:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
String todayString = today.format(dateFormatter);
System.out.println("Today is " + todayString);
Assert.assertEquals("Today " + todayString, dateOnWebpage);
Again, even though the pattern has one M and one d in it, two digits will be printed if the month or the day of month is greater than 9. What else could the format method do? If you require two-digit day of month always, put dd in the format pattern string.
In both snippets please fill in your desired time zone where I put Pacific/Norfolk since it is never the same date everywhere on the globe.
I am using and recommending java.time, the modern Java date and time API. DateFormat and SimpleDateFormat are not only long outdated, they are also notoriously troublesome. Date is just as outdated. I would avoid those classes completely. The modern API is generally so much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time.

Determine timezone from string "2016-09-14T00:00:00.000-07:00/2016-09-15T00:00:00.000-07:00"

My code is running with -Duser.timezone=UTC.
I am looking to create an Interval with the correct timezone from strings.
For example:
"2016-09-14T00:00:00.000-07:00/2016-09-15T07:00:00.000-07:00"
Interval.parse(str) should give me
[2016-09-14/2016-09-15] in PST.
But that always give me an Interval in UTC instead of PST b/c of -Duser.timezone=UTC option.
The only way I know of to solve this is tedious and involves the following steps:
Parse the string
Determine Offset
Find what timezone that offset corresponds to.
(whitelist? or someone has a list already?)
Then create a new Interval myself.
Is there a better way?
This should get you started:
String dateString = "2016-09-14T00:00:00.000-0700/2016-09-15T07:00:00.000-0700";
String datesInString[] = dateString.split("/");
SimpleDateFormat inputDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
outputDateFormat.setTimeZone(TimeZone.getTimeZone("PST"));
Date date0 = inputDateFormat.parse(datesInString[0]);
Date date1 = inputDateFormat.parse(datesInString[1]);
String result = outputDateFormat.format(date0) + "/"
+ outputDateFormat.format(date1) + " "
+ outputDateFormat.getTimeZone().getID();
System.out.println(result);

android getDate from milliseconds stored in String field

I have a date stored in a String field in SQLITE with the String value
"/Date(1411472160000+0100)/"
how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?
any suggestions ?
Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);
return dateFormat.format(convertedDate);
Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.
From there, I believe you can find the date ;)
String s = "/Date(1411472160000+0100)/";
s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
Date d = new Date(Long.parseLong(s));
With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.
First you have to parse out the time value from String i.e. "1411472160000+0100" part.
Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.
Approach-1
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
then to get the date in your specified format you can use-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
Besides this approach, there is an excellent Java Date library called JodaTime.
If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-

How to remove millisec from date and time [duplicate]

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;
}

convert java.sql.Timestamp to java.sql.Date

I have a Timestamp and Date variables and i want to compare it for equality (only date part of course). It was surprise for me that contructor Date(long) saves time part, so this code does not work correct:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
//...
if (date.equals(new Date (timestamp.getTime())) ...
I solve this with code like:
DateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd");
if (date.equals(dateFormat.parse(dateFormat.format(timestamp)))) ...
Or i can convert timestamp to date in sql query, but i need a timestamp representation too. Is there a better way to cut a time part from Timestamp.
Java 8 approach of conversion:
Date date = Date.valueOf(timestamp.toLocalDateTime().toLocalDate());
And vice versa:
Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
Using the method from this answer we get:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date);
cal2.setTimeInMillis(timestamp.getTime());
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
It's worth reading the linked answer as it talks about the shortcomings of this method with respects to timezones and so on (and some of the other answers to that question give alternate approaches which you may prefer).
You have three options with this one.
First is to use Yoda time and class DateTimeComparator.getDateOnlyInstance()
Second is to use commons from apache and DateUtils.isSameDay()
Third use the [Calendar] and set the time and compare the year, month and day of year only. As Dave Webb proposed.
Another approach is to use the "day" part of the epoch value:
Date d = new Date();
Timestamp t = new Timestamp(d.getTime());
long dateEpochDays = d.getTime() % (1000*60*60*24);
long timeStampEpochDays = t.getTime() %(1000*60*60*24);
System.out.println("date: " + dateEpochDays + " timestamp: " + timeStampEpochDays);

Categories

Resources