How get next date by passing current Date in java [duplicate] - java

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 8 years ago.
How do I get the next date(2014/03/21) given the current date(2014/03/20) in Java?
Code:
public static String getNextDate(String curDate) {
String nextDate="";
try {
//here logic to get nextDate
} catch (Exception e) {
return nextDate;
}
return nextDate;
}

Use SimpleDateFormat to get a Date-object from your string representation, then use Calendar for arithmetics followed by SimpleDateformat to convert the Date-object back to a string representation. (And handle the Exceptions I didn't do)
public static String getNextDate(String curDate) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
final Date date = format.parse(curDate);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
return format.format(calendar.getTime());
}

use java Calendar and you can use to do some date arithmetic such as adding day, months and years
public static String getNextDate(String curDate) {
String nextDate = "";
try {
Calendar today = Calendar.getInstance();
DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = format.parse(curDate);
today.setTime(date);
today.add(Calendar.DAY_OF_YEAR, 1);
nextDate = format.format(today.getTime());
} catch (Exception e) {
return nextDate;
}
return nextDate;
}

You can use Joda Time.
public static String getNextDate(String curDate) {
String nextDate="";
try {
LocalDate date = LocalDate.now();
date = date.plusDays(1);
nextDate = date.toString();
} finally {
return nextDate;
}
}

If you want a more native Java way you could split the string using String.split("/") and then add to the date part. However doing this requires that the carry is handled and that you track leap years.

Related

I have created a method to add minutes to date time but does not as expected in Java [duplicate]

This question already has answers here:
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Why is the month changed to 50 after I added 10 minutes?
(13 answers)
Closed 3 years ago.
This is a java code where it adds the date with time hours and minutes if a possible day to
timeAddition("06/20/2019;23:30", 60, "m")
public static String timeAddition(String TimeAndDate, int addTime, String units_M_H) {
try {
String returnTime = TimeAndDate;
final long ONE_MINUTE_IN_MILLIS = 60000;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY;HH:mm");
Date date = dateFormat.parse(TimeAndDate);
Calendar Cal = Calendar.getInstance();
Cal.setTime(date);
if (units_M_H.trim().equalsIgnoreCase("h")) {
Cal.add(Calendar.HOUR_OF_DAY, addTime);
returnTime = dateFormat.format(Cal.getTime()).toString();
} else if (units_M_H.trim().equalsIgnoreCase("m")) {
long timeInMili = date.getTime();
date = new Date(timeInMili + (addTime * ONE_MINUTE_IN_MILLIS));
returnTime = dateFormat.format(date);
}
return returnTime;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The expected output is 06/21/2019;00:30 but the actual output is 12/31/2019;00:30
java.time
Do not reinvent the wheel, Java already has all instruments to do such operations. See the java.time package of classes built into Java. See Tutorial.
String timestamp = "06/20/2019;23:30";
LocalDateTime ldt = LocalDateTime.parse(timestamp,
DateTimeFormatter.ofPattern("MM/dd/yyyy;HH:mm"));
System.out.println(ldt);
LocalDateTime ldt2 = ldt.plus(60L, ChronoUnit.MINUTES);
System.out.println(ldt2);
Will print that you expect.
2019-06-20T23:30
2019-06-21T00:30
Hope this helps!
Use yyyy for year.
YYYY represents week year.

Parsing String into date using java [duplicate]

This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
I am trying to parse string into a date using the following code:
public static Date dateFormatter(String s)
{
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate=null;
try
{
excelDate = ft.parse(s);
Date formatString = ft.format(excelDate);
System.out.println("Date to be printed in Excel is :" +formatString);
return excelDate;
}
catch(Exception ae)
{
System.out.println("No date");
}
return excelDate;
}
I am passing in the argument "04202017".
This function is not working for me. I am not able to figure out what I am doing wrong. Can anybody please help me?
You have to use ft.parse(s); instead of format(excelDate). Format is the other way (Date -> String)
DateFormat.parse(String)
And you dont have to parse the Date back to a String.
Corrected code:
public static Date dateFormatter(String s) {
SimpleDateFormat ft = new SimpleDateFormat ("MMddYYYY");
Date excelDate = null;
try {
excelDate = ft.parse(s);
System.out.println("Date to be printed in Excel is :" +excelDate);
return excelDate;
} catch(Exception ae) {
System.out.println("No date");
}
return excelDate;
}
You already parsed String s to excelDate with date format that you want. So i think it's good and enough to print just excelDate.
System.out.println("Date to be printed in Excel is :" +excelDate);
Like that.
And also change MMddYYYY to MMddyyyy.
Try parse method instead of format
For String to Date, use:
SimpleDateFormat.parse(String);
For Date to String, use:
SimpleDateFormat.format(date);
However, in your code, you already parsed the String and assigned into excelDate on this line:
excelDate = ft.parse(s);
try this one:
String string = "march 9, 2017";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
It would be nice to use Java 1.8's new time classes (which are in java.time.* package).
public static void main(String[] args)
{
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// To String
String dateString = dateTime.format(formatter);
System.out.println(dateString);
// To LocalDateTime
LocalDateTime parsedLocalDateTime = LocalDateTime.parse(dateString, formatter);
}

How to validate a date in Java? [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 7 years ago.
I have a date coming in this format -
2015-4-10T11:20:56
I need to validate the date and make sure date it is not greater than current date. Meaning if today is April 10th, then it should not be April 11th or greater than that.
String abc = "2015-4-10T11:20:56";
if(abc is greater than todays date) {
// log an error
}
How can I do this?
UPDATE:-
I tried parssing like this but it didn't worked -
String abc = "2015-4-10T11:20:56";
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(abc);
} catch (ParseException e) {
e.printStackTrace();
}
You have to convert the string to a date object.
You can use a SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
Date date = sdf.parse(dateStr);
if (date.compareTo(new Date()) > 0) {
// log an error
}
This should work for you:
String abc = "2015-4-10T11:20:56";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
Date mydate = df.parse(abc);
Calendar c = Calendar.getInstance();
c.setTime(mydate);
Calendar today = Calendar.getInstance();
if (c.compareTo(today)>=0){
}
You can try like this using compareTo
Date date = null;
String str = "2015-4-10T11:20:56";
try {
DateFormat f = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
f.setLenient(false);
date = f.parse(str);
if (date.compareTo(new Date()) > 0) {
// your code
}
} catch (ParseException e) {
e.printStackTrace();
}

How to get UTC time without SimpleDateFormat? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 8 years ago.
I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.
Read up on Joda-Time. That is a better API for such things than the java date and calendar classes
maybe this can help you:
Calendar.getInstance(java.util.TimeZone)
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.
So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {
public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private Date date = new Date();
private final SimpleDateFormat format;
public DateTimeHelper(String dateTimeFormat) {
format = new SimpleDateFormat(dateTimeFormat, Locale.US);
}
public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
this(dateTimeFormat);
try {
format.setTimeZone(timeZoneUTC);
Date utc = format.parse(utcTimeString);
format.setTimeZone(TimeZone.getDefault());
String local = format.format(utc);
date = format.parse(local);
} catch (ParseException e) {
// nothing
}
}
public Date getDate() {
return date;
}
public Date toUtc() {
String temp = toString();
format.setTimeZone(timeZoneUTC);
try {
return format.parse(temp);
} catch (ParseException e) {
return date;
}
}
#Override
public String toString() {
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
public String toUtcString() {
format.setTimeZone(timeZoneUTC);
return format.format(date);
}
}
And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {
public MySqlDateTimeHelper() {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
}
public MySqlDateTimeHelper(String utcTimeString) {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
}
public static String getCurrentTimestampUtc() {
MySqlDateTimeHelper current = new MySqlDateTimeHelper();
return current.toUtcString();
}
}

Android 4.3 jelly Bean Time format issue

My date format is this "yyyy-MM-dd" and when i get month using this function it return me wrong format of month. For example instead of "July" it return me only "J"
here is the function:
public static String getMonthName(String date) {
Date mDate = Utils.parseDate(date);
SimpleDateFormat sdf = new SimpleDateFormat("MMMMM");
String time = sdf.format(mDate);
return time;
}
andy idea what to do?
Edit:
and here is my parseDate(String date) function
public static Date parseDate(String date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
return formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return new Date();
}
}
I think you have one M to much
M:1
MM:01
MMM:Jan
MMMM:January
MMMMM:J

Categories