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"));
Related
Need to format this String 2017-08-01T15:43:45+0530 to 2017-08-01T15:43:45+05:30 using a particular date format. Tried with yyyy-MM-dd'T'HH:mm:ssZZ. Did not work..
Date modified = aemPage.getProperties().get(cq:lastModified, Date.class);
private DateFormat seoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
String formattedDate = seoDateFormat.format(modified));
You need three X to get off set like
Sign TwoDigitHours : Minutes
I suggest to use OffsetDateTime if you are working with java8 or higher:
String input = "2017-08-01T15:43:45+0530";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(input, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println(offsetDateTime.format(formatter)); // 2017-08-01T15:43:45+05:30
Since 2017-08-01T15:43:45+05:30 is ISO_OFFSET_DATE_TIME, you can also just use:
String outPut = offsetDateTime.toString();
Update:
If you want to use SimpleDateFormat, try:
String input = "2017-08-01T15:43:45+0530";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println(formatter.format(date));
But this only works when your system's offset is 0530 since Date does not hold time zone information.
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'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();
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)
How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)