I want to use a Date in XMLGregorianCalendar format for sending to a web service. The web service expects information in yyyy-dd-mm format. I use the below code to create an XMLGregorianCalendar and send it to web service.
Date dob = null;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
XMLGregorianCalendar date2;
dob = df.parse("13/06/1983");
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(dob.getTime());
date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
System.out.println(date2);
}
catch(DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately I always get the date as 1983-06-13T00:00:00.000-04:00. Time is also getting included in the output. Is it possible to get only the date? Could you please help me?
you don't need to specify a "SimpleDateFormat", it's simple:
You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
Much simpler using only SimpleDateFormat, without passing all the parameters individual:
String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date = new Date();
XMLGregorianCalendar gDateFormatted =
DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));
Full example here.
Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd.
Yeah Got it...
Date dob=null;
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
dob=df.parse( "13/06/1983" );
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dob);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
This will give it in correct format.
This is an easy way for any format. Just change it to required format string
XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
System.out.println(gregFmt);
There isn’t really an ideal conversion, but I would like to supply a couple of options.
java.time
First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.
DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateString = "13/06/1983";
LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
System.out.println(date);
The output is:
1983-06-13
Do you need to go any further? LocalDate.toString() produces the format you asked about.
Format and parse
Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date.toString());
System.out.println(xmlDate);
1983-06-13
Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.
Pass year, month and day of month individually
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);
The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.
Convert through GregorianCalendar
I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.
ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregCal);
xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.
Related
I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?
I want to declare a date using
Date birthday = new Date(y_birthday, m_birthday, d_birthday);
but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp
So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:
String text = "2011-12-12";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(text);
edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:
java.sql.Date date2 = new java.sql.Date(date.getTime());
Use a calendar object if you want more control of the date object
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());
The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)
If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates
I am using Java 6, and I have a time from the current date as a string, like this: 14:21:16, and I need to convert this to a Timestamp object to store in a database.
However there seems to be no good way to get a Timestamp from this. Timestamp.valueOf(String) is quite close, but requires a date. Is there a good way to make a Timestamp object from such a string?
How about this:
final String str = "14:21:16";
final Timestamp timestamp =
Timestamp.valueOf(
new SimpleDateFormat("yyyy-MM-dd ")
.format(new Date()) // get the current date as String
.concat(str) // and append the time
);
System.out.println(timestamp);
Output:
2011-03-02 14:21:16.0
Personally, I'd use Joda Time to parse the time to a LocalTime, and add that to today's LocalDate to get a LocalDateTime, then convert that into an Instant using whatever time zone you're interested in. (Or use LocalTime.toDateTimeToday(DateTimeZone).)
Then just create a time stamp using the Timestamp(long) constructor.
There are plenty of other approaches (e.g. using SimpleDateFormat instead of parsing with Joda Time, if you really want...) but ultimately you're likely to want the Timestamp(long) constructor in the end. (The benefit of using Joda Time here is that it's obvious what's being represented at each stage - you're not trying to treat a "time only" as a "date and time" or vice versa.)
Best I can come up with using standard API is not that pretty:
// Get today's date and time.
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
// Get the required time of day, copy year, month, day.
Calendar c2 = Calendar.getInstance();
c2.setTime(java.sql.Time.valueOf("14:21:16"));
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
// Construct required java.sql.Timestamp object.
Timestamp time = new Timestamp(c2.getTimeInMillis());
Let's see what we've done.
System.out.println(time);
Note that java.sql.Time.valueOf accepts a string of the form "HH:MM:SS" as you require. Other formats would require use of SimpleDateFormat.
Use org.apache.commons.lang.time.DateUtils:
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date time = df.parse("14:21:16");
Timestamp time = new Timestamp(today.getTime() + time.getTime());
Have a given day (say, unix epoch?) to serve as the day. When you use it, only use the time parameters that you care about, ignoring the day.
Another option would be java.sql.Time
http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Time.htm
String str = "14:21:16";
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = formatter.parse(str);
Timestamp timestamp = new Timestamp(date.getTime());
I have a String Object in format yyyyMMdd.Is there a simple way to get a String with previous date in the same format?
Thanks
I would rewrite these answers a bit.
You can use
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Get a Date object from the date string
Date myDate = dateFormat.parse(dateString);
// this calculation may skip a day (Standard-to-Daylight switch)...
//oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));
// if the Date->time xform always places the time as YYYYMMDD 00:00:00
// this will be safer.
oneDayBefore = new Date(myDate.getTime() - 2);
String result = dateFormat.format(oneDayBefore);
To get the same results as those that are being computed by using Calendar.
Here is how to do it without Joda Time:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
public static void main(String[] args) {
String dateString = "20100316";
try {
// This will print 20100315
System.out.println(previousDateString(dateString));
} catch (ParseException e) {
System.out.println("Invalid date string");
e.printStackTrace();
}
}
}
You can use:
Calendar cal = Calendar.getInstance();
//subtracting a day
cal.add(Calendar.DATE, -1);
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
String result = s.format(new Date(cal.getTimeInMillis()));
It's much harder than it should be in Java without library support.
You can parse the given String into a Date object using an instance of the SimpleDateFormat class.
Then you can use Calendar's add() to subtract one day.
Then you can use SimpleDateFormat's format() to get the formatted date as a String.
The Joda Time library a much easier API.
This is an old question, and most existing answers pre-date Java 8. Hence, adding this answer for Java 8+ users.
Java 8 introduced new APIs for Date and Time to replace poorly designed, and difficult to use java.util.Date and java.util.Calendar classes.
To deal with dates without time zones, LocalDate class can be used.
String dateString = "20200301";
// BASIC_ISO_DATE is "YYYYMMDD"
// See below link to docs for details
LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);
// get date for previous day
LocalDate previousDate = date.minusDays(1);
System.out.println(previousDate.format(DateTimeFormatter.BASIC_ISO_DATE));
// prints 20200229
Docs:
DateTimeFormatter.BASIC_ISO_DATE
LocalDate
use SimpleDateFormat to parse the String to Date, then subtract one day. after that convert the date to String again.
HI,
I want to get 20 days previous, to current date,
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR, - 20);
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
I had some UN Expected result, When i tried on Jan 11th,
Current Time Tue Jan 11 12:32:16 IST 2011
X Time Sat Dec 11 12:32:16 IST 2010
Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR,cal.getTime().getDate() - 20 );
System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
This code solved my Problem.
If you are willing to use the 3rd-party utility, Joda-Time, here is some example code using Joda-Time 2.3 on Java 7. Takes just two lines.
String dateAsString = "20130101";
org.joda.time.LocalDate someDay = org.joda.time.LocalDate.parse(dateAsString, org.joda.time.format.DateTimeFormat.forPattern("yyyymmdd"));
org.joda.time.LocalDate dayBefore = someDay.minusDays(1);
See the results:
System.out.println("someDay: " + someDay );
System.out.println("dayBefore: " + dayBefore );
When run:
someDay: 2013-01-01
dayBefore: 2012-12-31
This code assumes you have no time zone. Lacking a time zone is rarely a good thing, but if that's your case, that code may work for you. If you do have a time zone, use a DateTime object instead of LocalDate.
About that example code and about Joda-Time…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
you can create a generic method which takes
- Date (String) (current date or from date),
- Format (String) (your desired fromat) and
- Days (number of days before(-ve value) or after(+ve value))
as input and return your desired date in required format.
following method can resolve this problem.
public String getRequiredDate(String date , String format ,int days){
try{
final Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat(format).parse(date));
cal.add(Calendar.DATE, days);
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.format(cal.getTime());
}
catch(Exception ex){
logger.error(ex.getMessage(), ex);
}
return date;
}
}
In Java 8 we can use directly for this purpose
LocalDate todayDate = LocalDate.now();
By default it provide the format of 2021-06-07, with the help of formater we can change this also
LocalDate previousDate = todayDate.minusDays(5);
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.YEAR, -1);
Date dt2 = new Date(cal2.getTimeInMillis());
System.out.println(dt2);