Convert date format from php to Java? - java

I am working on a Streaming Android application which I have to convert some php codes to java.
How can I convert this date format from php to java?
$today = gmdate("n/j/Y g:i:s A");

This date format in php is interpreted like this:
n: Numeric representation of a month, without leading zeros
j: Day of the month without leading zeros
Y: A full numeric representation of a year, 4 digits
g: 12-hour format of an hour without leading zeros
i: Minutes with leading zeros
s: Seconds, with leading zeros
A: Uppercase Ante meridiem and Post meridiem - AM/PM
and the same date format in java is like this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M/d/yyyy h:mm:ss a");
String today = simpleDateFormat.format(new Date());

To get a new java.util.Date object from your PHP date string, in Java:
String phpDateString = "7/24/2016 12:21:44 am";
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy h:mm:ss a");
Date javaDate = sdf.parse(phpDateString);
System.out.println(javaDate);
System.out.println(sdf.format(javaDate));
Output:
Sun Jul 24 00:21:44 CEST 2016
7/24/2016 12:21:44 AM
OP's self-answer was very informative, but it had an error in the Java expression (it's lowercase h for am/pm hours) and didn't include code to actually parse the PHP string into a Java Date object, which was the original question.

Related

Generic date parsing in java

I have date strings in various formats like Oct 10 11:05:03 or 12/12/2016 4:30 etc
If I do
// some code...
getDate("Oct 10 11:05:03", "MMM d HH:mm:ss");
// some code ...
The date gets parsed, but I am getting the year as 1970 (since the year is not specified in the string.) But I want the year as current year if year is not specidied. Same applies for all fields.
here is my getDate function:
public Date getDate(dateStr, pattern) {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
Date date = parser.parse(myDate);
return date;
}
can anybody tell me how to do that inside getDate function (because I want a generic solution)?
Thanks in advance!
If you do not know the format in advance, you should list the actual formats you are expecting and then try to parse them. If one fails, try the next one.
Here is an example of how to fill in the default.
You'll end up with something like this:
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.parseDefaulting(YEAR, currentYear)
.toFormatter();
LocalDate date = LocalDate.parse("yourstring", f);
Or even better, the abovementioned formatter class supports optional elements. Wrap the year specifier in square brackets and the element will be optional. You can then supply a default with parseDefaulting.
Here is an example:
String s1 = "Oct 5 11:05:03";
String s2 = "Oct 5 1996 13:51:56"; // Year supplied
String format = "MMM d [uuuu ]HH:mm:ss";
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern(format)
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
.toFormatter(Locale.US);
System.out.println(LocalDate.parse(s1, f));
System.out.println(LocalDate.parse(s2, f));
Note: Dates and times are not easy. You should take into consideration that date interpreting is often locale-dependant and this sometimes leads to ambiguity. For example, the date string "05/12/2018" means the 12th of May, 2018 when you are American, but in some European areas it means the 5th of December 2018. You need to be aware of that.
One option would be to concatenate the current year onto the incoming date string, and then parse:
String ts = "Oct 10 11:05:03";
int currYear = Calendar.getInstance().get(Calendar.YEAR);
ts = String.valueOf(currYear) + " " + ts;
Date date = getDate(ts, "yyyy MMM d HH:mm:ss");
System.out.println(date);
Wed Oct 10 11:05:03 CEST 2018
Demo
Note that we could have used StringBuilder above, but the purpose of brevity of code, I used raw string concatenations instead. I also fixed a few typos in your helper method getDate().

SimpleDateFormat Always returning 12.30 AM [duplicate]

This question already has answers here:
Simple date formatting giving wrong time
(4 answers)
Closed 7 years ago.
I am trying to utilise the Calendar apart from implementing my own logic.
I am setting the Calendar value and trying to get the time in a format, below is the code
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy HH:mm a");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(timeValue));
Logger.d(TAG, "Hour is = " + calendar.get(Calendar.HOUR));
SimpleDateFormat slotTime = new SimpleDateFormat("hh:mma");
SimpleDateFormat slotDate = new SimpleDateFormat(", dd/MM/yy");
Logger.d(TAG, " Date = " + slotDate.format(calendar.getTime()) + " Time is = " + slotTime.format(calendar.getTime()));
}catch (ParseException parseEx){
parseEx.printStackTrace();
}
I am expecting slotTime.format(calendar.getTime())) should return 6.30 PM while it is returning 12.30 AM.
How can I get the desired output which is 6.30 PM , What mistake I am doing
Your code is OK. The mistake is on the datetime mask:
The ".SSS" field is too much. This is only to expect for milliseconds, and, as far as I can see, you do not expect milliseconds in your input string.
The "HH" mask should be "hh" for 1-12 hours format.
Thus, let it be:
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a");
You have to remove milliseconds from your Simple Date Format (SSS).
I get a java.text.ParseException running your code.
Try using a Simple Date Format string of "dd/MM/yyyy HH:mm a"
you have an error with the String in the time format
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a.SSS");
a.SSS // .SSS is for Millisenconds which is not correct in the String you are trying to parse.
I removed it and worked fine for me.
Take a look at DateFormat.getTimeInstance(), DateFormat.getDateInstance() and DateFormat.getDateTimeInstance() as these methods return a DateFormat which will honor the users local settings (e.g. 12/24 hour system or date formats like 2016/01/01 or 01.01.2016). This is very important if you plan to release your app in multiple languages. Note that these methods also take a int as parameter with which you can style the resulting format (e.g. short format).
See here for more details.
A complete example would llok like this (creates a String like 3:04 PM on devices with English language and 15:04 on devices with e.g. German language):
String s = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(new Date()); // Creates a String like 3:04 PM

How to convert Gregorian string to Gregorian Calendar?

I have to compute something based on the Calendar's date, but I am receiving the complete Gregorian Calendar's String value.
Eg i/p received {may be - "new GregorianCalendar().toString()"} as String :- java.util.GregorianCalendar[time=1410521241348,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=8,WEEK_OF_YEAR=37,WEEK_OF_MONTH=2,DAY_OF_MONTH=12,DAY_OF_YEAR=255,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=27,SECOND=21,MILLISECOND=348,ZONE_OFFSET=0,DST_OFFSET=3600000]
I want to extract the Calendar's date value to process further computation.
You could find the time in the input string and convert it to a Gregorian Calendar. Then you would have to set its timezone as specified in the ZoneInfo field. Something like this might work:
String calendarAsString="java.util.GregorianCalendar[time=1410521241348,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id=\"Europe/London\",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=8,WEEK_OF_YEAR=37,WEEK_OF_MONTH=2,DAY_OF_MONTH=12,DAY_OF_YEAR=255,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=27,SECOND=21,MILLISECOND=348,ZONE_OFFSET=0,DST_OFFSET=3600000]";
int timeStart=calendarAsString.indexOf("time=")+5;
int timeEnd=calendarAsString.indexOf(',');
String timeStr=calendarAsString.substring(timeStart, timeEnd);
long timeInMillis=Long.parseLong(timeStr);
int timezoneIdStart=calendarAsString.indexOf("\"")+1;
int timezoneIdEnd=calendarAsString.indexOf("\",");
String timeZoneStr=calendarAsString.substring(timezoneIdStart, timezoneIdEnd);
System.out.println("time="+timeInMillis+" zone="+timeZoneStr);
Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone(timeZoneStr));
calendar.setTimeInMillis(timeInMillis);
System.out.println(calendarAsString);
System.out.println(calendar);
or you can use a regular expression to do it, instead
String regex="time=([0-9]*),.*ZoneInfo\\[id=\"([^\"]*)\"";
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(calendarAsString);
matcher.find();
timeStr=matcher.group(1);
timeInMillis=Long.parseLong(timeStr);
timeZoneStr=matcher.group(2);
System.out.println("time="+timeInMillis+" zone="+timeZoneStr);
calendar=Calendar.getInstance(TimeZone.getTimeZone(timeZoneStr));
calendar.setTimeInMillis(timeInMillis);
System.out.println(calendar);
Note: if you just want the calendar's Date value, you can construct it from the timeInMillis, without having to reconstruct the whole GregorianCalendar object (and without having to find the timezone if you don't want to).
Date date=new Date(timeInMillis);
Other answers are too complicated or wrong. The following will give you the milliseconds since the epoch, which is a universal timestamp that you can easily convert to most time representation classes, including Calendar or Date:
Pattern gregorianPattern = Pattern.compile("^java.util.GregorianCalendar\\[time=(\\d+).*");
Matcher matcher = gregorianPattern.matcher(param);
if(matcher.matches()) {
return Long.parseLong(matcher.group(1));
}
GregorianCalendar g=new GregorianCalendar(1975, 5, 7);
Date d=g.getTime();
System.out.println(g.toString());
SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM dd");
System.out.println(formatter.format(d));
This is way to grab date from GregorianCalendar. i wish this will help to you
Adding more to this, you can retrieve any information you want using the format. It's just a matter of providing the correct format.
Ex:
Adding z or Z provides you with the timezone information
"yyyy MM dd z" - 2014 10 12 PDT
"yyyy MM dd Z" - 2014 10 12 -0700
Adding a 'T' would result in something like this:
"yyyy-MM-dd'T'HH:mm:ss.sssZ" - 2014-10-12T14:23:51.890+0530
In this HH represents hours in 24 hour format mm minutes ss seconds sss milliseconds.

How to format date for use in a URL as a parameter

I am using an API to get a weather forecast up until a particular date in Java.
The requirement for passing a date as a URL parameter is that it must be in "YYYY-MM-DD'T'HH:MM:SS" format. I get input in this format from the user, then get the current system date, and then loop until the desired date. The problem lies in converting the input date string into the date format, incrementing it by one day, and then converting it back to the string format for URL parameter.
I am using the following code to do this but it is giving me incorrect results:
formatter = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
Date date1 = formatter.parse(inputtime);
System.out.println(date1);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
c1.add(Calendar.DAY_OF_MONTH, 1); // number of days to add
inputtime = formatter.format(c1.getTime()); // dt is now the new date
System.out.println(c1.getTime());
System.out.println(inputtime);
inputtime is the input by the user. If I give "2014-04-12T00:00:00" as inputtime, date1 is then "Sun Dec 29 00:00:00 PKT 2013", c1.getTime() returns "Mon Dec 30 00:00:00 PKT 2013" and inputtime becomes then "2014-12-364T00:12:00" according to the above code block.
How can this logic error be corrected?
You should consider SimpleDateFormat date and time patterns: link
For example, something like this:
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Have a try to change your date pattern from
new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
to
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Letter Date or Time Component Presentation Examples
y Year Year 1996; 96
M Month in year Month July; Jul; 07
D Day in year Number 189
d Day in month Number 10
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
That format is defined by the ISO 8601 standard. The Joda-Time library follows that standard's formats as a default for both parsing and generating strings. So does the new java.time package in Java 8.
Your string omits a time zone offset. So, you need to know and specify the time zone intended by that string. Perhaps the time zone is UTC meaning a time zone offset of zero.
A day is not always 24 hours. If you meant 24 hours rather than 1 day, call the method plusHours( 24 ).
Here is example code in Joda-Time 2.3.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.UTC;
DateTime dateTime = new DateTime( input, timeZone );
DateTime tomorrow = dateTime.plusDays( 1 );
String outputWithOffset = tomorrow.toString();
String output = ISODateTimeFormat.dateHourMinuteSecond().print( tomorrow );

Parsed date has minute difference

So I am trying to parse a date string in Java. I am getting the correct hours back but the minutes seem to be out by about 5-10. I am showing my code below along with the input string and the date Objects toString() output.
Any ideas where I am going wrong? This is on Android so I would prefer not to use JodaTime.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
Date date = sdf.parse(input);
return date;
Input String = 2012-11-07T12:47:05.0581816Z
Date toString() = Wed Nov 07 12:56:46 GMT 2012 (Milliseconds = 1352293006816)
You are trying to parse a date with microsecond precision as millisecond precision.
0581816 is the number of milliseconds added to the time 12:47:05, not, as you probably expect, a decimal fraction of a second.
Since the precision below millisecond cannot be represented by java.util.Date, the simplest option would be to truncate the decimal fraction and adjust the date format, as follows:
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = "2012-11-07T12:47:05.058234234Z";
input = input.replaceFirst("(?<=\\.\\d{3})\\d+", "");
System.out.println(input);
System.out.println(sdf.parse(input));
Please make sure you are using the same time zone while converting a String to a date object and vice-versa

Categories

Resources