Processing Java Strings and Dates - java

I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?

public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)
.getTime() returns the time in milliseconds. It's part of the java.util.Date API.

Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);

Related

Using Date instead of Timestamp

My code:
Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
I want to eliminate the use of time stamp in this situation, how can achieve the same thing here with epochTimeStamp without using java.sql.Timestamp? I need the format to be same as if I was using Timestamp.
Since you need a String representation of your Date, then use SimpleDateFormat to convert the Date object into a String:
Calendar calendar = ...
//...
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
System.out.println(sdf.format(date));
System.out.println(sdf.format(epochTimeStamp));
} catch (Exception e) {
//handle it!
}
From your example, prints
01/01/1970 09:21:18
01/01/1970 09:21:18
This gives you the epoch time in the same format as TimeStamp:
public class FormatDate {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS");
LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println(datetime.format(format));
}
}
Another way to represent date time objects in Java is to use the Joda Time libraries.
import org.joda.time.LocalDate;
...
LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00");
//or DateTime startDate = new DateTime ();// creates instance of current time
String formatted =
startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss");
There are several ways to do formatting, setting and getting Time using these libraries that has been more reliable than using the JDK Date and Calendar libraries. These will persist in hibernate/JPA as well. If nothing else, this hopefully gives you options.

Difference between date in miliseconds and its Calendar representation

I have two functions which convert a date String to a date in milliseconds:
public static long convertYYYYMMDDtoLong(String date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d = f.parse(date);
long milliseconds = d.getTime();
return milliseconds;
}
If I run this function I get the following result:
long timeStamp = convertYYYYMMDDtoLong("2014-02-17");
System.out.println(timeStamp);
It prints:
1389909720000
Now, if I run the following code:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
System.out.println(cal.getTime());
It prints out:
Fri Jan 17 00:02:00 IST 2014
Why is my date shifted by one month? What is wrong?
P.S: My problem is that I need to map the date, represented as long, to another third party API which accepts Calendar format only.
You're using mm, which is minutes, not months. You want yyyy-MM-dd as your format string.
It's not clear why you're not returning a Calendar directly from your method, mind you:
private static final TimeZone UTC = TimeZone.getTimeZone("Etc/UTC")
public static Calendar convertYYYYMMDDtoCalendar(String text) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(UTC);
Calendar calendar = new GregorianCalendar(UTC);
calendar.setDate(format.parse(text));
return calendar;
}
(That's assuming you want a time zone of UTC... you'll need to decide that for yourself.)

Fast way to parse a Long date into Month-Day-Year String

How do you parse a Long date like: 1366222239935 into a String of space-separated Month-Day-Year? Like into "Apr 18 2013"
Passing it on a java.util.Date and to a String will give a String of date which contains so many info that I don't need for rendering in my GWT application.
Need to do this style since I will be passing the result into 3 <span> elements; so actually the space-separated date will be split into parts:
Month
Day
Year
As gwt won't support SimpleDateFormat
instead use Gwt DateTimeFormat
DateTimeFormat f = DateTimeFormat.getFormat("dd-MMM-yyyy");
String datestring =f.format(dateGeneratedbyLong);
And make sure the DateTimeFormat import also which you can use both client and server side .
There is another class with same name but package is different which is client(restricts you to use on client side only )
try to use SimpleDataFormat check http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html>
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateAsString = simpleDateFormat.format(new Date());
You could convert it to a Date and then manually build your String like this.-
Date date = new Date(timeInMils);
String res = date.get(Calendar.MONTH) + " " +
date.get(Calendar.DAY_OF_MONTH) + " " +
date.get(Calendar.YEAR);
That Long number is simply the number of milliseconds since the JavaScript epoch (1/1/1970 at midnight, UTC time). So, instead of parsing it, use the constructor for the Date object:
var myDate = new Date(1366222239935);
alert(myDate);
That will show "Wed Apr 17 2013 11:10:39 GMT-0700 (Pacific Daylight Time)". I am in PST, but it will default to whatever timezone you have in your locale settings.
Inside a GWT app in Java, simply do:
Date date=new Date(1366222239935);
Then you can use SimpleDateFormat to render it as "dd/MM/yy".
See http://www.w3schools.com/jsref/jsref_obj_date.asp
Do like this
Date d = new Date();
d.setTime(1366222239935l);
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy");
try {
System.out.println(sdf.format((d)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = 1366222239935l;
Date date = new Date(diff);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println(sdf.format(date));

Incrementing date in yyyymmddhhmmss.mmm format in Java

I want to increment the milliseconds in any given date in the format yyyymmddhhmmss.mmm in each iteration. mmm here represents milliseconds. And I want to perfom this operation in Java 1.5.
For example: 20120823151034.567 should be incremented to 20120823151034.568
You can use long milli-seconds which make incrementing trivial.
final String input = "20120823151034.567";
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date d = df.parse(input);
d.setTime(d.getTime()+1);
System.out.println(df.format(d));
I wouldn't use Calendar as its very slow.
You can parse String to Date object and use getTime() and setTime(long l) to modify date. Then you can convert Date object back to String. For parsing String and converting Date object back to String you can use SimpleDateFormat class.
The best class to use for this operation is Calendar. You set it to the desired date, and then use
myCalendar.add(Calendar.MILLISECOND, 1);
to advance it by one millisecond. Use DateFormat to produce string representations.
This gives you what you want. It will work across any day/month/year boundary, as well as handling the start and end of daylight saving time.
final String input = "20120823151034.567";
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
c.add(Calendar.MILLISECOND, 1);
System.out.println(df.format(c.getTime()));
You can use Calendar Class as well as Date Class for this....
Date Class:
final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date date = format.parse(input);
date.setTime(date.getTime()+1);
System.out.println(format.format(date));
Calendar Class:
final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(dateStr ));
c.add(Calendar.MILLISECOND,1);
System.out.println(format.format(c.getTime()));
In both cases, format.parse() has the potential to throw a ParseException, which you will need to catch and handle.
An alternative without using Calendar (although, Calendar is fine)
final String input = "20120814120000.111";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date date = new format.parse(input);
long time = date.getTime();
Date incrementedDate = new Date(time + 1);
System.out.println(format.format(date));

How to format a date String into desirable Date format

I was trying to format a string into date.
For this I have written a code:-
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdf.format( cal.getTime() ));
This is fine..
But now I want to convert a string into a date formatted like above..
For example
String dt="2010-10-22";
And the output should be like this:-
2010-10-22T00:00:00
How do I do this?
String dt = "2010-10-22";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition ps = new ParsePosition(0)
Date date = sdfIn.parse(dt, pos)
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdfOut.format( date ));
This should do it for you, remember to wrap it in a try-catch block just in case.
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try
{
Date today = dt.parse("2010-10-22T00:00:00");
System.out.println("Your Date = " + dt.format(today));
} catch (ParseException e)
{
//This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
//Black Magic Goes Here
}
If your input is going to be ISO, you could also look at using the Joda Time API, like so:
LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
System.out.println("Formatted time: " + localDateTime.toString());
The same class you use for output formatting of dates can also be used to parse dates on input.
SimpleDateFormat reference
To use your example, to parse the sample date:
String dt = "2010-10-22";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormatter.parse(dt));
The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.
Date Format Example
Containing the Conversion of String Date object from one format to another

Categories

Resources