java php strtotime

Strtotime de PHP() en Java



(5)

strtotime () en PHP puede hacer las siguientes transformaciones:

Insumos:

strtotime(’2004-02-12T15:19:21+00:00′); strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′); strtotime(’Monday, January 1st’); strtotime(’tomorrow’); strtotime(’-1 week 2 days 4 hours 2 seconds’);

Productos:

2004-02-12 07:02:21 2000-12-21 06:12:07 2009-01-01 12:01:00 2009-02-12 12:02:00 2009-02-06 09:02:41

¿Hay alguna manera fácil de hacer esto en Java?

Sí, esto es un duplicate Sin embargo, la pregunta original no fue respondida. Por lo general, necesito la capacidad de consultar fechas del pasado. Quiero darle al usuario la capacidad de decir ''Quiero todos los eventos desde'' -1 semana ''hasta'' ahora ''''. Hará que escribir estos tipos de solicitudes sea mucho más fácil.


Hasta donde yo sé, nada de esto existe. Deberías hackear uno tú mismo. Sin embargo, puede que no sea necesario. Trate de almacenar las fechas como marcas de tiempo y simplemente haciendo las matemáticas simples. Entiendo que esto no es tan limpio como te gustaría. Pero funcionaría.


Mira JodaTime , creo que es la mejor biblioteca de fecha y hora para Java.


Puede usar el formato de fecha simple para tal cosa, pero debe conocer el formato de fecha antes de analizar la cadena. PHP intentará adivinarlo, Java espera que le digas explícitamente qué hacer.

Ejemplo:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); SimpleDateFormat formater = new SimpleDateFormat("MM/dd/yy"); Date d = parser.parse("2007-04-23 11:22:02"); System.out.println(formater.format(d));

Emite:

04/23/2007

SimpleDateFormat fallará silenciosamente si la cadena no está en el formato correcto, a menos que configure:

parser.setLenient(false);

En ese caso, arrojará java.text.ParseException.

Para el formateo avanzado, use el DateFormat y sus numerosos operators .


Use un calendario y formatee el resultado con SimpleDateFormat:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

Calendar now = Calendar.getInstance(); Calendar working; SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd ''at'' hh:mm:ss a zzz"); working = (Calendar) now.clone(); //strtotime("-2 years") working.add(Calendar.DAY_OF_YEAR, - (365 * 2)); System.out.println(" Two years ago it was: " + formatter.format(working.getTime())); working = (Calendar) now.clone(); //strtotime("+5 days"); working.add(Calendar.DAY_OF_YEAR, + 5); System.out.println(" In five days it will be: " + formatter.format(working.getTime()));

Bien, es significativamente más prolijo que el strtotime de PHP (), pero al final del día, es la funcionalidad que buscas.


Intenté implementar una clase simple (estática) que emula algunos de los patrones del strtotime de PHP. Esta clase está diseñada para estar abierta a modificaciones (simplemente agregue un nuevo Matcher través de 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(); } }

Uso

Uso básico:

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

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

Extensión

Por ejemplo, agreguemos días 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; } });

entonces puedes escribir:

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

(ahora es Wed Aug 12 22:18:57 CEST 2009 )

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