简体   繁体   中英

Coverting PHP statement into Java

I had to convert the following PHP script into a JSP scriplet:

<?php
 $cache_expire = 60*60*24*365;
 header("Pragma: public");
 header("Cache-Control: max-age=".$cache_expire);
 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
?>

I was able to do:

<%! long cacheExpire = 60*60*24*365; %>

<% 
 response.setHeader("Pragma", "public");
 response.setHeader("Cache-Control", "max-age=" + cacheExpire);
 response.setHeader("Expires", "....?..."); // what do I put in the second string ?
%>

But I am unable to convert the last statement in the PHP script to JSP. I just understood this in Java:

new GregorianCalendar().getTime() + cacheExpire

but this is incorrect to implement.

How do I convert the last statement of PHP to a Java one?

This is the exact equivalent of your PHP code above:

<%! long cacheExpire = 60*60*24*365; %>

<% 
 response.setHeader("Pragma", "public");
 response.setHeader("Cache-Control", "max-age=" + cacheExpire);

 DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
 df.setTimeZone(TimeZone.getTimeZone("GMT"));
 long expire = (long) System.currentTimeMillis() + (cacheExpire * 1000);
 String expires = df.format(new Date(expire)) + " GMT";

 response.setHeader("Expires", expires);
%>

tricky part was convert between different date format tokens of java and php and get the java date on GMT timezone, hope you find it useful :-)

尝试这个:

response.setDateHeader("Expires", System.currentTimeMillis() + cacheExpire);

You have to use Calender.get(Calendar.YEAR) etc. to achieve this. There is no way of expressing date format in Java the way you can do it in PHP, however, you can get field values just the same.

You should use SimpleDateFormat class to format the Date object in Java. For example, check the following code, replace stringDatePattern by valid date format like "yyyy-MM-dd" .

new SimpleDateFormat(stringDatePattern).format(new Date()) + cacheExpire

In the above snippet, new Date() returns the current time, which is formatted using SimpleDateFormat as per the pattern passed. Then you just concatenate the cacheExpire variable.

That example does exactly what you want:

int cacheExpire = 60 * 60 * 24 * 365;

Calendar cal = Calendar.getInstance();
cal.add( Calendar.SECOND, cacheExpire );
SimpleDateFormat format = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss 'GMT'" );
format.setTimeZone( TimeZone.getTimeZone( "GMT" ) );

response.setHeader( "Expires", format.format( cal.getTime() ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM