Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a Date from a String [duplicate]

I have to compare two dates in if/else, the current date and the predefined date (let's say 1 Jan 2011). This was supposed to be simple, but I can't find the way to set the predefined date something like:

Java.util.Date date = new Date("2011-01-01");

How to compare two dates? I really don't know why it's so complicated to do.

like image 750
sandalone Avatar asked May 04 '11 17:05

sandalone


People also ask

How do I turn a string into a Date?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

Can we cast string to Date?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes. To learn this concept well, you should visit DateFormat and SimpleDateFormat classes.

How do you convert a string to a Date in JavaScript?

You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.


2 Answers

Try:

import java.text.SimpleDateFormat;
import java.util.Date;

...

Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01");

if(today.equals(predefined)) {
    ...
}
like image 84
Rob Hruska Avatar answered Sep 28 '22 16:09

Rob Hruska


Use java.util.Calendar.

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
Date predefined = cal.getTime();

Date now = new Date();

if (now.after(predefined))
{
    // do something
}
else
{
    // do something else
}

or use JodaTime.

How to compare two dates? I really don't know why it's so complicated to do.

Because calendars/dates/times are really hard to get right, and the Java implementation of Date (and, in part Calendar) is an utter train wreck.

like image 26
Matt Ball Avatar answered Sep 28 '22 17:09

Matt Ball