I have a code that displays time in GMT and I need to show it in PST. How can I modify the below code to get the time in PST?
Code
public static final String FORMAT = "MM/dd/yyyy";
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static final String INPUT_FORMAT_STD_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
formatDate is being called here
public void endElement(String uri, String localName, String qName) throws SAXException {
if( EVENT.equalsIgnoreCase( qName ) ) {
auditEntries.add(entry);
} else if( LOG_TIME.equalsIgnoreCase( qName ) ) {
String time = content.toString();
entry.setLogTime( DateUtils.formatDate(time, "yyyy-MM-dd'T'HH:mm:ss", DateUtils.OUTPUT_FORMAT_STD_DATE6));
}
Please help, I am new b in writing Java code.
This is how I am doing it.
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
DateFormat pstFormat = new SimpleDateFormat( outputFormat );
pstFormat.setTimeZone( TimeZone.getDefault() );
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
Thanks
Once you have a Date object you can convert it to a timezoned string using SimpleDateFormat. Below is a simple example.
Using 3 letter timezone IDs has been deprecated, so you should use GMT+-hour:minute format, or region specific string like America/Los_Angeles as suggested by #VGR
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
Ref:https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTest {
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static void main(String[] args) {
Date date = new Date();
String gmtDateStr = dateToTimzoneString(date, "GMT", OUTPUT_FORMAT_STD_DATE6);
System.out.println(gmtDateStr);
//3 Letter String usage is deprecated
String pstDateStr = dateToTimzoneString(date, "PST", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
//Correct way
pstDateStr = dateToTimzoneString(date, "GMT+5", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
}
public static String dateToTimzoneString(Date date, String timeZoneStr, String outputFormat){
SimpleDateFormat sd = new SimpleDateFormat(outputFormat);
sd.setTimeZone(TimeZone.getTimeZone(timeZoneStr));
return sd.format(date);
}
}
This is how I did it.
public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
String displayDateString = null;
try {
DateFormat inFormat = new SimpleDateFormat( inputFormat );
inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
Date date = inFormat.parse( strDate );
DateFormat outFormat = new SimpleDateFormat( outputFormat );
outFormat.setTimeZone( TimeZone.getDefault() );
displayDateString = formatDate(date, outputFormat);
} catch ( ParseException pe ) {
pe.printStackTrace();
}
return displayDateString;
}
Related
I want to get traces following logs
{
#Aspect
#Component
public class AspectJPay {
private static final Logger log = LoggerFactory.getLogger(AxiPayCustomerController.class);
#Before("execution(* lk.ideahub.symphony.controller.axipay.customer.AxiPayCustomerController.*(..))")
public void logBefore(JoinPoint joinPoint) {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate = dateFormat.format(date);
log.info("Current Start time Time is : {} {}", formattedDate, joinPoint.getSignature().getName());
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
#After("execution(* lk.ideahub.symphony.controller.axipay.customer.AxiPayCustomerController.*(..))")
public void logAfter(JoinPoint joinPoint) {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate = dateFormat.format(date);
log.info("Current End Time is : {} {}", formattedDate, joinPoint.getSignature().getName());
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
}
}
But non of the logs getting traced. did anyone know why i`m wrong or i want to know the actual gradle dependencies which want to import
Please help me
Thanks.
I am making a date filter for which I have created a custom method for date to be parse in specific date format.
I have date with to two formats dd MMM yyyy & yyyy-mm-dd which is passed in a single method to be parse and return in format of yyyy-mm-dd. As I have a complex structure at end both type of formatted string will go under the date parsing method.
ISSUE:: I am getting a blank string as return from this method when format is in yyyy-mm-dd. please provide me inputs of where i am wrong. Below is the code
//fetching date from methods
String current_date=CurrentFilterPeriod.dateParsing("2017-04-02");
String prev_date=CurrentFilterPeriod.dateParsing("01 Apr 2017");
//singleton file for date filter method
public class CurrentFilterPeriod {
private static Calendar cal = getInstance();
private static Date current_date = cal.getTime();
//defined formats for date
private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
private static SimpleDateFormat formatterString = new SimpleDateFormat("yyyy-MM-dd");
//method for parsing date
public static String dateParsing(String date){
Date newDate;
String returnDate = "";
if (date.equals(formatter.toPattern())){
returnDate=date;
}
Log.e("DB","date===>"+date);
try {
newDate = formatter.parse(date);
Log.e("DB","New Date===>"+newDate);
returnDate=formatterString.format(newDate);
Log.e("DB","returnDate===>"+returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
}
RESULT:: current_date="" prev_date="2017-04-01"
I am stuck here please help me or tell me other methods to get by desired output.Want result in format of yyyy-mm-dd
As you want result format like: yyyy-mm-dd. You need to check your Date String with formatterString formatter.
Change your code with:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(String input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
Now call the method using:
//method for parsing date
public static String dateParsing(String date) {
Date newDate;
String returnDate = "";
if (isValidDate(date)) {
returnDate = date;
return returnDate;
} else {
Log.e("DB", "date===>" + date);
try {
newDate = formatter.parse(date);
Log.e("DB", "New Date===>" + newDate);
returnDate = formatterString.format(newDate);
Log.e("DB", "returnDate===>" + returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return returnDate;
}
I have a Date in string format "01-23-2004".
I want to split the date and insert every day/month/year to a different filed in a web form.
I did this:
public static void dateInString()
{
String dt = "01-23-2004";
String dateParts[] = dt.split("-");
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
}
public void insertBirthDateBounus() throws IOException, ParserConfigurationException, SAXException
{
comOps.selectDropDown(birthdayMonth,day);
comOps.selectDropDown(birthdayDay, mounth);
comOps.selectDropDown(birthdayYear, year);
}
And I received an error msg that day, mounth, year - cant be resolved by variable.
( comOps.selectDropDown is the select from drop down list to select a date. This was written in a different class with all my common methods )
Use like this .
1.Let month 、day and year as global variables
2.Use it in insertBirthDateBounus method
private static String month;
private static String day;
private static String year;
public static void dateInString() {
String dt = "01-23-2004";
// 1.format first
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy",Locale.ENGLISH);
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM-dd-yyyy",Locale.ENGLISH);
Date date = null;
try {
date = sdf1.parse(dt);
String newDate= sdf2.format(date);
System.out.println(newDate);
// 2.split
String[] dateParts = newDate.split("-");
month = dateParts[0];
day = dateParts[1];
year = dateParts[2];
System.out.println(month);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void insertBirthDateBounus() throws IOException, ParserConfigurationException, SAXException {
comOps.selectDropDown(birthdayMonth, day);
comOps.selectDropDown(birthdayDay, month);
comOps.selectDropDown(birthdayYear, year);
}
We need to change the date format of the default openxava date(javaSript) component. default format is MM/dd/yy, and we need to change it to MM/dd/yyyy.
With the below link we can change the format of list view with implementing IFormatter interface. but in this conversation not clearly mention how to change the format of the date selection component.
https://sourceforge.net/p/openxava/discussion/419690/thread/40db1436/
Please help me to fix this issue...
To change the way a date, or any other type, is parsed and formatted you have to define a formatter for that type. To define a formatter edit the editors.xml file and add an entry like this:
<editor name="DateCalendar" url="dateCalendarEditor.jsp">
<formatter class="com.yourcompany.yourapp..formatters.YourDateFormatter" />
<for-type type="java.util.Date" />
</editor>
You have to write YourDateFormatter that implements IFormatter. For example, the default formatter for date is this:
package org.openxava.formatters;
import java.text.*;
import javax.servlet.http.*;
import org.openxava.util.*;
/**
* Date formatter with multilocale support. <p>
*
* Although it does some refinement in Spanish case, it support formatting
* on locale basis.<br>
*
* #author Javier Paniza
*/
public class DateFormatter implements IFormatter {
private static DateFormat extendedDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // Only for some locales like "es" and "pl"
private static DateFormat [] extendedDateFormats = { // Only for some locales like "es", "fr", "ca" and "pl"
new SimpleDateFormat("dd/MM/yy"),
new SimpleDateFormat("ddMMyy"),
new SimpleDateFormat("dd.MM.yy")
};
public String format(HttpServletRequest request, Object date) {
if (date == null) return "";
if (Dates.getYear((java.util.Date)date) < 2) return "";
return getDateFormat().format(date);
}
public Object parse(HttpServletRequest request, String string) throws ParseException {
if (Is.emptyString(string)) return null;
if (isExtendedFormat()) {
if (string.indexOf('-') >= 0) { // SimpleDateFormat does not work well with -
string = Strings.change(string, "-", "/");
}
}
DateFormat [] dateFormats = getDateFormats();
for (int i=0; i<dateFormats.length; i++) {
try {
dateFormats[i].setLenient(false);
return dateFormats[i].parseObject(string);
}
catch (ParseException ex) {
}
}
throw new ParseException(XavaResources.getString("bad_date_format",string),-1);
}
private boolean isExtendedFormat() {
return "es".equals(Locales.getCurrent().getLanguage()) ||
"ca".equals(Locales.getCurrent().getLanguage()) ||
"pl".equals(Locales.getCurrent().getLanguage()) ||
"fr".equals(Locales.getCurrent().getLanguage());
}
private DateFormat getDateFormat() {
if (isExtendedFormat()) return extendedDateFormat;
return DateFormat.getDateInstance(DateFormat.SHORT, Locales.getCurrent());
}
private DateFormat[] getDateFormats() {
if (isExtendedFormat()) return extendedDateFormats;
return new DateFormat [] { getDateFormat() };
}
}
Is it possible to handle different date format in a Spring MVC controller?
I know that setting something like this
#InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
I can handle dd/MM/yyyy format, but what if i want to parse also dates in yyyyMMddhhmmss format? Should I add multiple CustomDateEditors in my controller?
If you need it only at puntual cases, you can register the custom editor attached to a field in the form:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", this.getLocale(context));
DateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss SSS", this.getLocale(context));
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateTimeFormat, true));
binder.registerCustomEditor(Date.class, "name.of.input", new CustomDateEditor(dateTimeFormat, true));
Inspired by Skipy
public class LenientDateParser extends PropertyEditorSupport {
private static final List<String> formats = new ArrayList<String>();
private String outputFormat;
static{
formats.add("dd-MM-yyyy HH:ss");
formats.add("dd/MM/yyyy HH:ss");
formats.add("dd-MM-yyyy");
formats.add("dd/MM/yyyy");
formats.add("dd MMM yyyy");
formats.add("MMM-yyyy HH:ss");
formats.add("MMM-yyyy");
formats.add("MMM yyyy");
}
public LenientDateParser(String outputFormat){
this.outputFormat = outputFormat;
}
#Override
public void setAsText(String text) throws IllegalArgumentException {
if(StringUtils.isEmpty(text))
return;
DateTime dt = null;
for(String format : formats){
try{
dt = DateTime.parse(text, DateTimeFormat.forPattern(format));
break;
}catch(Exception e){
if(log.isDebugEnabled())
log.debug(e,e);
}
}
if(dt != null)
setValue(dt.toDate());
}
#Override
public String getAsText() {
Date date = (Date) getValue();
if(date == null)
return "";
DateTimeFormatter f = DateTimeFormat.forPattern(outputFormat);
return f.print(date.getTime());
}
}
How about this. the above can go out of whack pretty soon.
public class MostLenientDateParser {
private final List<String> supportedFormats;
public MostLenientDateParser(List<String> supportedFormats) {
this.supportedFormats = supportedFormats;
}
public Date parse(String dateValue) {
for(String candidateFormat: supportedFormats) {
Date date = lenientParse(dateValue, candidateFormat);
if (date != null) {
return date;
}
}
throw new RuntimeException("tried so many formats, non matched");
}
private Date lenientParse(String dateCandidate, String dateFormat) {
try {
return new SimpleDateFormat(dateFormat).parse(dateCandidate);
} catch (Exception e) {
return null;
}
}
}
This could also be referenced through Spring Converters via a CustomDateEditor implementation for form-data binding.
For others having the same question, if you are using spring 3 You can use the awesome #DateTimeFormat(pattern="dd-MM-yyyy") in the field of your model.
Just make sure to register a conversionService with your org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
You can have as much as you want of #DateTimeFormat in the same bean.
If at a time you receive only one format of date, then you could simply create one instance of DateFormat based on format
for example
Decide the format based on the input
DateFormat df = null;
if(recievedDate.indexOf("//")!=-1){
df = new SimpleDateFormat("dd/MM/yyyy")
}else{
df = new SimpleDateFormat("yyyyMMddhhmmss")
}
Not a great idea to have lenient date formatters when dealing with multiple locales. A date like 10/11/2013 will get parsed correctly with both dd/MM/YYYY and MM/dd/YYYY