Experts,
I would like to get current datetime in a given timezone for global usage.
So,
I create a class like below, but it shows syntax error for the df.setTimeZone statement. What is the neat way to achieve this? More specific, I would like to set timezone property for a class member rather than a local variable.
I defined many date format through SimpleDateFormat, how to specify a timezone for all of them? (.setTimeZone seems only for one date format) Thanks.
public class Global {
static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));
static String strDate = df.format(new Date());
}
If you absolutely must do it with static fields, you need the code to be in a static initializer block:
class Global {
static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
static {
df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));
}
static String strDate = df.format(new Date());
}
UPDATE
If you have lot of dates to do like that, with different date formats and/or time zones, it may be better to use a helper method.
class Global {
static String strDate = format(new Date(), "dd/MM/yyyy", "GIVEN_TIMEZONE");
private static String format(Date date, String format, String timeZoneID) {
SimpleDateFormat df = new SimpleDateFormat(format);
df.setTimeZone(TimeZone.getTimeZone(timeZoneID));
return df.format(date);
}
}
Please try in below possible syntax:
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // Important line
Date date = readDate.parse(dtc);
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00")); // Important line
String s = writeDate.format(date);
You need to import below class:
https://developer.android.com/reference/java/util/TimeZone.html
Related
I'm trying to convert a resultset from ddMMyyyy HH:mm:ss (ex: 19/06/2022 00:00:10) to yyyyMMddHHmmss (should be 20220619000010) with SimpleDateFormate without success. This is how I'm doing:
I have an Util class, which has the follow class:
public class Utils {
public static String Format(String formato, Date date) {
date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
}
And I also have a ResultSet class witch return the objects of my query based in another class. Example:
Class one:
public class MyFile {
String Date = new String ();
+ getter and setter
}
Class 2 (create the line of my document):
public static MyFile createRow (ResultSet rs) throws SQLException {
MyFile mf = new MyFile();
mf.setDate(Utils.Format(rs.getString("Date");
return mf;
}
The point is: This conversion doesn't work and I can't find another way to do this. Someone could help me, please?
The java message:
"The method Format(String, Date) in te type Utils is not applicable for the arguments (String)
3 quick fixes available:
+ add argument to match 'Format(String, Date)'
- Change method 'Format(String, Date)': Remove parameter 'Date'
º Create method 'Format(String) in type 'Utils'"
For the conversion, you'll need two SimpleDateFormats; one for parsing the string to date, another to turn the date to the desired format:
public static String Format(String formato, Date date) {
SimpleDateFormat inputFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
try {
date = new inputFormat.parse(formato);
} catch (ParseException ex) {
// wrong format?
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dataString = sdf.format(date);
return dataString;
}
// usage
mf.setDate(Utils.Format(rs.getString("Date"), new Date()));
I presume your date parameter would be a default Date in case the formato input string is invalid.
If you want to do it with the packages java.time and java.time.format you can try something like this. Of course java.util.Date is stored essentially as milliseconds from the epoch without time zone, hence using UTC below. If you want the output to correspond to a particular time zone, then change it:
public static String formatDate(Date d) {
String result = null;
Instant i = Instant.ofEpochMilli(d.getTime());
ZonedDateTime zdt = ZonedDateTime.ofInstant(i, ZoneId.of("UTC"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
result = fmt.format(zdt);
return result;
}
First of all, I want to tell you that there are newer and more convenient libraries than the old java.util.Date library. I am not so experienced with the new ones, but mostly java.util.time (like here: Understanding Java util Date) or joda.time are recommended.
So maybe you want to consider using one of the newer library instead of the old SimpleDateFormat from java.util.Date, if you only just began coding with Dates and just picked the first library coming to your mind, I think it could be a good idea.
To your specific problem: The java error message just tells you how it is, in your utils class you have your String Format with the constructor with two input params, a String and a date. In this line:
mf.setDate(Utils.Format(rs.getString("Date");
you are calling your Utils.Format String, but you are only passing one argument, "rs.getString("Date")". So either you refactor your String Format Constructor to only take a string as an argument or you pass (like recommended in the java message) a string and a date, for instance like:
mf.setDate(Utils.Format(rs.getString("Date"), new Date();
While I'm writing this, I think in this line two closing brackets are missing. You should add them.
But I think it should not be that complicated to convert a String like 19/06/2022 00:00:10 into another format using SimpleDateFormat. All you need to do is
String sDate1="19/06/2022 00:00:10";
SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMddHHmmss");
Date date1=formatter1.parse(sDate1);
This way, in date1 should be your DateString in the Format you specified when initialising your SimpleDateFormat formatter1.
Here is the official doc to SimpleDateFormat: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Thnx for your answers, but I couldn't make any work.
So, I tried another way with success. It is:
public static String Format (String date) {
String formattedDate= date.substring(0, 4)
+ date.substring(5, 7)
+ date.substring(8, 10)
+ date.substring(11, 13)
+ date.substring(14, 16)
+ date.substring(17, 19);
return formattedDate;
}
mf.setDate(Utils.Format(rs.getString("Date");
I am trying to parse the date to look like 03-23-2015 21:16:00 GMT+05:00 using joda-time but i am not able to achieve it, however it is working fine with SimpleDateFormat but for some reason i want to use Joda-Time (see my question on SO.)
Please note that i don't want to hardcode timezone to GMT+05:00 but i want to set the user's default timezone.
I am trying it as:
public class Consts{
public static final DateTimeFormatter DATE_FORMATTER_2 = DateTimeFormat
.forPattern("MM-dd-yyyy HH:mm:ss z");
public static final DateTimeFormatter DATE_FORMATTER_TEMP_1 = DateTimeFormat
.forPattern("MM-dd-yyyy HH:mm:ss Z");
}
And then i am using these formatters as:
cDate = new LocalDateTime(DateTimeZone.getDefault());
sDate = new LocalDateTime(DateTimeZone.getDefault());
eDate = new LocalDateTime(DateTimeZone.getDefault());
if (mStartTimeTV.getText().toString().equals("Now")) {
sDate = cDate;
} else {
sDate = Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parseLocalDateTime(mStartTimeTV.getText().toString());
}
if (!mEndTimeTV.getText().toString().equals("")) {
eDate = Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parseLocalDateTime(mEndTimeTV.getText().toString());
} else {
eDate = sDate;
}
And while sending the dates to the server i am formatting them as:
String s0 = Consts.DATE_FORMATTER_2.print(sDate);
String s = Consts.DATE_FORMATTER_2.withZone(
DateTimeZone.getDefault()).print(sDate);
String s1 = Consts.DATE_FORMATTER_TEMP_1.print(sDate);
But the output is always: 03-24-2015 16:07:23
I have also tried with ZZZZ but no luck.
LocalDateTime doesn't have a time zone, so there is nothing to format. You should use DateTime instead, which you can obtain using LocalDateTime.toDateTime(timeZone).
I am writing a converter method that would parse an xml string data to java objects. But i am not able to parse dates to date objects.
How to format this date string "2013-08-26T12:00:00.000" in the following way: "2013-08-26 12:00:00" to Date object in java?
Edited to add the below code snippet.
Here is what I tried to do.
public Object fromString(String str) {
DateFormat dateFormat = DateFormat.getDateInstance();
try {
Date date = dateFormat.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
You should google these things first.
Here you go:
public static void main(String[] args) {
String inFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS";
String outFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
try {
Date d = sdf.parse("2013-08-26T12:00:00.000");
sdf.applyPattern(outFormat);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// handle appropriately
e.printStackTrace();
}
}
You can parse any Date-like string to Date object (as long as the the string represents a valid date) using http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
There is no point in re-formatting the String.
In order to process XML-date-time-strings which are allowed to be of variable precision (sometimes leaving out second- or fraction-part or timezone-offset) the use of SimpleDateFormat is not a good option because then you would only have one pattern. Not flexible.
Alternative for XML:
String xml = "2013-08-26T12:00:00.000"; // maybe optionally with additional timezone offset
javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar xmlGregCal = factory.newXMLGregorianCalendar(xml);
java.util.Date d = xmlGregCal.toGregorianCalendar().getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = outputFormat.format(d);
Watch also out for some overloaded methods to change the timezone settings for parsing and formatting - see the javadoc.
You may try this:
public static void main(String[] args) throws Exception {
String original = "2013-08-26T12:00:00.000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S").parse(original);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.printf("Before: %s\nAfter: %s\n", original, format);
}
OUTPUT:
Before: 2013-08-26T12:00:00.000
After: 2013-08-26 12:00:00
I am storing date values within a SQLite database in the format 20121224 (so that I can easily sort the database by date) my question is how can I get the date from the format "20121224" to "2012/12/24" after being extracted from the database using java code.
You can do this.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test003 {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
String s = "20121224";
Date dt = sdf1.parse(s);
System.out.println(sdf2.format(dt));
}
}
private static final String DATE_FORMAT = "yyyy/MM/dd";
private static final SimpleDateFormat dateFormat = new
SimpleDateFormat(DATE_FORMAT);
public static long dateAsLong(Calendar cal){
return Long.parseLong(dateFormat.format(cal.getTime()));
}
public static Calendar dateAsCalendar(long l){
try {
Calendar c = Calendar.getInstance();
c.setTime(dateFormat.parse(String.valueOf(l)));
return c;
} catch (ParseException e) {
return null;
}
}
Hope this helps.
In Java, Strings are immutable, so you can't modify the String you get back from the database; you have to make a new one. Easiest way, if your dates are guaranteed to be in yyyyMMdd format (ie, you don't store January as "01"), and you just want another String to come out the other end:
StringBuilder date = new StringBuilder();
date.append(dateStr.substring(0,4));
date.append("/");
date.append(dateStr.substring(4,6));
date.append("/");
date.append(dateStr.substring(6,8));
// use date.toString() wherever you need it
However, I'd recommend looking into how SQLite recommends you store dates. These are common formats and will allow you to use Java's built-in Date and DateFormat class in more conventional and convenient ways.
I see someone else has beaten me to submitting an answer while I was typing this...that suggestion will work, but it has you constructing 2 SimpleDateFormat objects, which isn't necessarily the most efficient way to go. Depends on how often you're doing this.
You can use the strftime function
Syntax:
strftime(timestring, modifiers...)
This returns the date formatted according to the format string specified
Example:
SELECT strftime('%d-%m-%Y') from TABLE_NAME;
Output:
24-11-2013
You can find all the formatters here
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");