I'm just starting to look at the JODA library and I want to take the current time and see if it falls within 3 days of a timestamp in the DB.
I'm looking at the example on their API:
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
I am taking a String from the database to create a Date object:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date)formatter.parse(startDate);
How can I see if Date object in my code falls within 3 days of the current time?:
Period threeDays = new Period().withDays(3);
boolean withinThreeDays = date.plus(threeDays).isBeforeNow();
You can get not parse Joda date from string, and check without SimpleDateFormat and Period
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = dtf.parseDateTime(startDate);
boolean withinThreeDays = dateTime.plusDays(3).isBeforeNow();
Related
I have a date stored in a String field in SQLITE with the String value
"/Date(1411472160000+0100)/"
how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?
any suggestions ?
Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);
return dateFormat.format(convertedDate);
Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.
From there, I believe you can find the date ;)
String s = "/Date(1411472160000+0100)/";
s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
Date d = new Date(Long.parseLong(s));
With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.
First you have to parse out the time value from String i.e. "1411472160000+0100" part.
Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.
Approach-1
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
then to get the date in your specified format you can use-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
Besides this approach, there is an excellent Java Date library called JodaTime.
If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-
I want to convert a date object, ex: new Date(), to a string which has a format like Oracle's time stamp type, ex: 21-OCT-13 11.08.13.858000000 AM. I know I could just get each piece of information in the date object like day, month, year, hour, minute, ... to form the Oracle format string but I really want to know is there a utility to do that instead?
Using SimpleDateFormat#format() you would print a Date as
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS a");
System.out.println(sdf.format(new Date()).toUpperCase());
Output :
21-OCT-13 10.01.38.000000614 AM
See JavaDocs for Date and Time patterns.
Try taking a look at SimpleDateFormats - That would be your best bet and easiest way of doing it.
Eg:
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); //Hours:Minutes:Seconds
String strDate = dateFormat.format(date);
Use SimpleDateFormat.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("your_format_here"); // dd/MM/yy h:mm:ss a
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
I want the current date and time in the following format :
Date :YYYYMMDD
Time : HHMMSS
I tried the following
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(new Date().getTime());
By this I am getting the desired date output but the time is coming in this way 1341837848290.
The expected is HHMMSS.
Use format()
System.out.println(new SimpleDateFormat("HH:mm:SS").format(new Date()));
Date instance doesn't have any property to hold custom format, So you need to format the date instance to String with your custom format HH:mm:SS (See API doc for more detail)
See
IDEOne demo
try this
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
DateFormat timeFormat = new SimpleDateFormat("HHmmss");
Date d=new Date();
System.out.println(timeFormat.format(d);
Did you check out the joda-time library? Link here
With joda-time, you could easily call new DateTime(), call toString() on it and have this output, which may be more what you want:
public static void main(final String[] args) {
final DateTime d = new DateTime();
System.out.println(d.toString());
}
Output: 2012-07-09T14:54:13.366+02:00
Joda-Time is very powerful on the plus side. Of course, this is an extra lib you need to include, and if this is not possible or desired, another approach would probably be better.
I tried this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
Date date = Calendar.getInstance().getTime();
System.out.println(sdf.format(date));
Yields:
20120709 145518
First section is the date (20120709), the second section is the time(145518).
It seems that you have been using the wrong notation. I would recommend you take a look here for full details.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:SS");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
for more formatting refer API Doc
I have seen this question asked multiple times and none of the answers seem to be what i need.
I have a long type variable which has an epoch time stored in it.
What i want to do is convert it to a String
for example if the epoch time stored was for today the final string would read:
17/03/2012
How would i to this?
Look into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.format(new Date(myTimeAsLong));
You'd create a Date from the long - that's easy:
Date date = new Date(epochTime);
Note that epochTime here ought to be in milliseconds since the epoch - if you've got seconds since the epoch, multiply by 1000.
Then you'd create a SimpleDateFormat specifying the relevant pattern, culture and time zone. For example:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(...);
Then use that to format the date to a string:
String text = format.format(date);
Date date = new Date(String);
this is deprecated.
solution
Date date = new Date(1406178443 * 1000L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
make sure multiply by 1000L
If the method should be portable, better use the default (local time) TimeZone.getDefault():
String epochToIso8601(long time) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date(time * 1000));
}
try this
Date date = new Date(1476126532838L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));//your zone
formatted = format.format(date);
System.out.println(formatted);
Joda-Time
If by epoch time you meant a count of milliseconds since first moment of 1970 in UTC, then here is some example code using the Joda-Time library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( yourMilliseconds, timeZone );
String output = DateTimeFormat.forStyle( "S-" ).withLocale( Locale.CANADA_FRENCH ).print( dateTime );
Other Epochs
That definition of epoch is common because of its use within Unix. But be aware that at least a couple dozen epoch definitions are used by various computer systems.
Time for someone to provide the modern answer (valid and recommended since 2014).
java.time
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.US);
String facebookTime = "1548410106047";
long fbt = Long.parseLong(facebookTime);
ZonedDateTime dateTime = Instant.ofEpochMilli(fbt).atZone(ZoneId.of("America/Indiana/Knox"));
System.out.println(dateTime.format(formatter));
The output is:
January 25, 2019 at 3:55:06 AM CST
If you wanted only the date and in a shorter format, use for example
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.US);
1/25/19
Note how the snippet allows you to specify time zone, language (locale) and how long or short of a format you want.
Links
Oracle tutorial: Date Time explaining how to use java.time.
My example string was taken from this duplicate question
Try this...
sample Epoch timestamp is 1414492391238
Method:
public static String GetHumanReadableDate(long epochSec, String dateFormatStr) {
Date date = new Date(epochSec * 1000);
SimpleDateFormat format = new SimpleDateFormat(dateFormatStr,
Locale.getDefault());
return format.format(date);
}
Usability:
long timestamp = Long.parseLong(engTime) / 1000;
String engTime_ = GetHumanReadableDate(timestamp, "dd-MM-yyyy HH:mm:ss aa");
Result:
28-10-2014 16:03:11 pm
You need to be aware that epoch time in java is in milliseconds, while what you are converting may be in seconds. Ensure that both sides of the conversions are in milliseconds, and then you can fetch the date parameters from the Date object.
ArLiteDTMConv Utility help converting EPOUCH-UNIX Date-Time values, Form EPOUCH-UNIX-To-Date-format and Vise-Versa. You can set the result to a variable and then use the variable in your script or when passing as parameter or introduce in any DB criteria for both Window and Linux. (Download a zip file on this link)
I used following code to convert string to date but it is applying timezone of device while conversion.
I don't need this but I want same date/time from that string like
String = "2009-07-31 07:59:17.427"
Date = 2009-07-31 07:59:17.427
Date formatter = new Date(HttpDateParser.parse("2009-07-31 07:59:17.427"));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strCustomDateTime = dateFormat.format(formatter);
You may take in account default timezone offset to date you get after parsing:
public static String StringToDate(String dateToParse) {
Date formatter = new Date(HttpDateParser.parse(dateToParse));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
int offset = TimeZone.getDefault().getRawOffset();
formatter.setTime(formatter.getTime() + offset);
String strCustomDateTime = dateFormat.format(formatter);
return strCustomDateTime;
}
What is the problem, exactly? You are trying to convert "2009-07-31 07:59:17.427" into a point in time, but, this does not specify a unique point in time -- without a timezone. So you do need a timezone, and the library is necessary picking one, the platform's current timezone.
If the problem is you wish to specify a different time zone, then call DateFormat.setTimeZone():
format.setTimeZone(TimeZone.getTimeZone("your time zone"));