This question already has answers here:
Date object to Calendar [Java]
(8 answers)
Closed 6 years ago.
So I get a date attribute from an incoming object in the form:
Tue May 24 05:05:16 EDT 2011
I am writing a simple helper method to convert it to a calendar method, I was using the following code:
public static Calendar DateToCalendar(Date date )
{
Calendar cal = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
cal=Calendar.getInstance();
cal.setTime(date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
return cal;
}
To simulate the incoming object I am just assigning the values within the code currently using:
private Date m_lastActivityDate = new Date();
However this is givin me a null pointer once the method reaches:
date = (Date)formatter.parse(date.toString());
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
Just use Apache Commons
DateUtils.toCalendar(Date date)
it's so easy...converting a date to calendar like this:
Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();
Related
This question already has answers here:
Datetime parsing error
(2 answers)
Closed 5 years ago.
I am struggling with a date string, I need to parse into the java ‘Date’ object.
Here is what I have got so far:
try {
String value = "2017-11-23T14:00:49.184000000Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'";
SimpleDateFormat parser = new SimpleDateFormat(pattern);
Date date = parser.parse(value);
} catch (ParseException e) {e.printStackTrace();}
It currently throws a ParseException “Unparseable date” and I can’t get it to work.
Any help is highly appreciated!
Thanks
Use Instant from java.time package (java 8) instead, it should look like below
String value = "2017-11-23T14:00:49.184000000Z";
Instant instant = Instant.parse(value);
Date date = Date.from(instant);
System.out.println(date);
you can use timeZone as well like this as another solution.
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'");
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2017-11-23T14:58:00.184000000Z"));
Date date = cal.getTime();
System.out.println(date);
This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
Below is the code which generates the output as "9/2/2014"
public static void main (String[]args) throws ParseException
{
java.util.Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("M/d/yyyy");
System.out.println(sd.format(d));
}
Now i need to add some n no of days and i wanted to get the output as 9/12/2014
please help me ...
If you want add month, or days to your date, use something like that:
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
to add month use Calendar.Month
Calendar has methods for date manipulations. First create Calendar instance and set date to it
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Then you can use calendar instance to add days like
calendar.add(Calendar.DATE,10);
to get date from calendar, use
System.out.println(calendar.getTime());
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to subtract X day from a Date object in Java?
(10 answers)
Closed 8 years ago.
Can any one help me with the code for adding some number of days to any date..?
For example today is 11-04-2014. I want 15-04-2014 + 3 days output:18-04-2014.
My question is not adding dates to current date..
With Java 8, you can write:
import java.time.LocalDate;
LocalDate date = LocalDate.of(2014, 4, 11);
LocalDate newDate = date.plusDays(3);
System.out.println(newDate); // Prints 2014-04-14
Its that simple.
String dateString = "11-04-2014" // Say you have a date in String format
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); // Create an instance of SimpleDateFormat with the right format.
Date date = format.parse(dateString); // Then parse the string, this will need a try catch statement.
Calendar calendar = Calendar.getInstance(); // Get an instance of the calendar.
calendar.setTime(date); // Set the time of the calendar to the parsed date
calendar.add(Calendar.DATE, 3); // Add the days to the calendar
String outputFormat = format.format(calendar.getTime());
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class A {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2012);
calendar.add(Calendar.DAY_OF_MONTH, 3);
System.out.println(simpleDateFormat.format(calendar.getTime()));
}
}
You can use the calendar function:
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, NO_OF_DAYS_TO_ADD);
Date addedDays = cal.getTime();
DateInstance is the date you are using. addedDays can be formatted using SimpleDateFormat to display in any date format that you would like to use.
I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?
public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)
.getTime() returns the time in milliseconds. It's part of the java.util.Date API.
Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);
I am trying to get the program to call up the current date, add 30 days to it, and then out put that date as a string.
// Set calendar for due date on invoice gui
Calendar cal = Calendar.getInstance();
// Add 30 days to the calendar for the due date
cal.add(Calendar.DATE, 30);
Date dueDate = cal.getTime();
dueDatestr = Calendar.toString(dueDate);
And the question is?
If you want to format your date, I suggest looking at java.text.SimpleDateFormat instead of using toString(). You can do something like:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate); // renders as 11/29/2009
You almost have it:
Date dueDate = cal.getTime();
String dueDateAsString = dueDate.toString();
or
String dueDateAsFormattedString = DateFormat.format(dueDate);
You might want to consider using FastDateFormat from Apache commons, instead of SimpleDateFormat, because SimpleDateFormat is not thread safe.
FastDateFormat dateFormat = FastDateFormat.getInstance("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate);
This is especially true if you wanted to use a static instance of the date formatter, which is a common temptation.
You can do it easily with a class of mine:
https://github.com/knyttl/Maite/wiki/Maite-Date-and-Time
new Time()
.plus(1, Time.DAY)
.format("yyyy-MM-dd");