Php's Strtotime() in Java

PHP's strtotime() in Java

I tried to implement a simple (static) class that emulates some of the patterns of PHP's strtotime. This class is designed to be open for modification (simply add a new Matcher via registerMatcher):

public final class strtotime {

private static final List<Matcher> matchers;

static {
matchers = new LinkedList<Matcher>();
matchers.add(new NowMatcher());
matchers.add(new TomorrowMatcher());
matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z")));
matchers.add(new DateFormatMatcher(new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z")));
matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy MM dd")));
// add as many format as you want
}

// not thread-safe
public static void registerMatcher(Matcher matcher) {
matchers.add(matcher);
}

public static interface Matcher {

public Date tryConvert(String input);
}

private static class DateFormatMatcher implements Matcher {

private final DateFormat dateFormat;

public DateFormatMatcher(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}

public Date tryConvert(String input) {
try {
return dateFormat.parse(input);
} catch (ParseException ex) {
return null;
}
}
}

private static class NowMatcher implements Matcher {

private final Pattern now = Pattern.compile("now");

public Date tryConvert(String input) {
if (now.matcher(input).matches()) {
return new Date();
} else {
return null;
}
}
}

private static class TomorrowMatcher implements Matcher {

private final Pattern tomorrow = Pattern.compile("tomorrow");

public Date tryConvert(String input) {
if (tomorrow.matcher(input).matches()) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, +1);
return calendar.getTime();
} else {
return null;
}
}
}

public static Date strtotime(String input) {
for (Matcher matcher : matchers) {
Date date = matcher.tryConvert(input);

if (date != null) {
return date;
}
}

return null;
}

private strtotime() {
throw new UnsupportedOperationException();
}
}

Usage

Basic usage:

 Date now = strtotime("now");
Date tomorrow = strtotime("tomorrow");

Wed Aug 12 22:18:57 CEST 2009
Thu Aug 13 22:18:57 CEST 2009

Extending

For example let's add days matcher:

strtotime.registerMatcher(new Matcher() {

private final Pattern days = Pattern.compile("[\\-\\+]?\\d+ days");

public Date tryConvert(String input) {

if (days.matcher(input).matches()) {
int d = Integer.parseInt(input.split(" ")[0]);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, d);
return calendar.getTime();
}

return null;
}
});

then you can write:

System.out.println(strtotime("3 days"));
System.out.println(strtotime("-3 days"));

(now is Wed Aug 12 22:18:57 CEST 2009)


Sat Aug 15 22:18:57 CEST 2009
Sun Aug 09 22:18:57 CEST 2009

Difference between SimpleDateFormat and strtotime?

PHP strtotime()

  • Parse about any English textual datetime description into a Unix timestamp

Unix timestamp:

  • the number of seconds since January 1 1970 00:00:00 UTC

This

echo strtotime("2013-08-30");

will return 1377835200


Java Date.getTime()

  • Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This

System.out.println(date.getTime());

will return 1377831600000.

Which means you should perform

System.out.println(date.getTime() / 1000);

Also, in case of discrepancies, check your timezones.

PHP date conversion to strtotime

You need to understand over here the date format of your date.
Here m/d/Y is considered to be the standard American Date format.

So when your date is like

'09/06/2014',//it should be considered as 06 september 2014
'04/07/2014',//it should be considered as 07 april 2014

And when your date is like as

'21/05/2014',
'22/05/2014',

Then the above date doesn't fits within the standards of American Date Format i.e. m/d/Y instead what you can do over here is replace / along with - which converts your date into European Date Format which is d-m-Y

Coldfusion equiv of PHP strtotime()?

I don't know of a way in coldfusion (not natively anyway) that will take a textual representation of time and do a conversion. A few google searches also did not turn up anything. It could be written but would not be a simple undertaking.

That said, if you want to get a date 1 week back, you could do something like this using the dateadd() function:

<cfset variables.lastweek = dateAdd("w",-1,now()) />

or

<cfset variables.lastweek = dateAdd("d",-7,now()) />

Of course you can substitute now() out for any timestamp or date.

Update:

Remember that because CF is java, you can use any java classes to help you on your way too. It doesn't look like there is a cut and dry equivallent even in java, but these relevant topics may help you on your way:

PHP's strtotime() in Java?

PHP's strtotime() in Java

Have I gone crazy, or has PHP's strototime() broke?

There's a hidden character in your code, if I copy your code into https://sandbox.onlinephpfunctions.com/, there's a red marked char in your string.

If I remove this, it works and prints out a timestamp.

How algorithm of strtotime(PHP Date function) Works?

You can browse the source code of PHP ( https://github.com/php/php-src) and search function to see its implementation.

UPDATE

Here is the algorithm of the function strtotime () https://github.com/php/php-src/blob/master/ext/date/php_date.c#L1324

Regards!.

How to pass java.util.Date to Java library with help of php-java bridge

It was simple, just a problem I had from the beginning in php code.

    $query = new java("net.sf.jasperreports.engine.design.JRDesignQuery");

$jasperDesign->setQuery($query);

This code was preventing xrml query from executing, because it was creating a query object empty.

strtotime shows current year for previous dates

The strtotime() function can only convert a limited number of formats, as detailed in the Supported Date and Time Formats section in the PHP manual.

The following note from the Date Formats page is pertinent in this case as the 2018 part of your example is interpreted as a 24-hour time value.

Note:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

You could use string manipulation (e.g. use preg_replace() or str_replace() to remove the ,) to provide a date format that PHP interprets as you want. I would prefer using a regex, eg:

$sd = "20th Dec, 2016";
echo date("y", strtotime(preg_replace("/([\w ]+),([\w ]+)/", "$1$2", $sd)));

A good alternative would be to use DateTime::createFromFormat(), with which you state exactly the format that the date string has.

$sd = "20th Dec, 2016";
$dt = DateTime::createFromFormat("dS M, Y", $sd);
echo $dt->format("d-M-Y");
echo strtotime($dt->format("d-M-Y"));


Related Topics



Leave a reply



Submit