This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 8 years ago.
I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.
Read up on Joda-Time. That is a better API for such things than the java date and calendar classes
maybe this can help you:
Calendar.getInstance(java.util.TimeZone)
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.
So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {
public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private Date date = new Date();
private final SimpleDateFormat format;
public DateTimeHelper(String dateTimeFormat) {
format = new SimpleDateFormat(dateTimeFormat, Locale.US);
}
public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
this(dateTimeFormat);
try {
format.setTimeZone(timeZoneUTC);
Date utc = format.parse(utcTimeString);
format.setTimeZone(TimeZone.getDefault());
String local = format.format(utc);
date = format.parse(local);
} catch (ParseException e) {
// nothing
}
}
public Date getDate() {
return date;
}
public Date toUtc() {
String temp = toString();
format.setTimeZone(timeZoneUTC);
try {
return format.parse(temp);
} catch (ParseException e) {
return date;
}
}
#Override
public String toString() {
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
public String toUtcString() {
format.setTimeZone(timeZoneUTC);
return format.format(date);
}
}
And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {
public MySqlDateTimeHelper() {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
}
public MySqlDateTimeHelper(String utcTimeString) {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
}
public static String getCurrentTimestampUtc() {
MySqlDateTimeHelper current = new MySqlDateTimeHelper();
return current.toUtcString();
}
}
Related
I have a Date object in DTO object:
public class TopTerminalsDTO {
private Date date;
private int volume;
private int count;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
When I get the response in Angular I get
count: 1
date: "2018-10-06T00:00:00.000+0000"
volume: 111
I want to get this date format YYYY-MM-DD HH:mm:ss in Angular.
What is the proper way to convert the Date into the DTO object? Is it better to use LocalDateTime?
It's better to use LocalDateTime object, but it will return it with a T between the date and hours. You should remove it like in the selected answer here LocalDate - How to remove character 'T' in LocalDate
U can use DateFormat to convert your desire date format.
TopTerminalsDTO tt = new TopTerminalsDTO();
tt.setDate(new Date());
String strDateFormat = "YYYY-MM-DD HH:mm:ss";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(tt.getDate());
System.out.println(formattedDate);
As you are sending rest object to angular so u can use string field as date in DTO once covert it in desire date format.
User the Below Code.
Date myDate = new Date();
System.out.println(new SimpleDateFormat("YYYY-MM-DD HH:mm:ss").format(myDate));
LocalDate is the preferred way of many developers since it's been released in Java 8. You can format a LocalDate object the way you want by using the .format(DateTimeFormatter) method of LocalDate.
Like this example from: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
Edit:
The LocalDate class doens't provide a time representation. Therefore if you like to also have time, use the LocalDateTime class. The .format() method of LocalDateTime can be used like the .format() method of LocalDate as shown above.
I am trying to convert string in java.util.date but I am having following errors:
HelloWorld.java:10: error: incompatible types: Date cannot be converted to String
return FORMATTER.parse(date);
^
HelloWorld.java:16: error: incompatible types: String cannot be converted to Date
Date date = convertStringToDate("2015-08-03 09:19:00.000");
My code is below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld{
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static String convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}
public static void main(String []args){
Date date = convertStringToDate("2015-08-03 09:19:00.000");
System.out.println(date);
}
}
Change your method signature into this instead:
public static Date convertStringToDate(String date)
SimpleDateFormat.parse returns a Date, not a String.
Also, you need to handle the checked ParseException that the parse method may throw, either by declaring throws ParseException in the signature (and handling the exception in main), or by wrapping the exception into a RuntimeException (effectively terminating the program when bad input is given):
public static Date convertStringToDate(String date) {
if (date != null) {
try {
return FORMATTER.parse(date);
} catch (ParseException e) {
// nothing we can do if the input is invalid
throw new RuntimeException(e);
}
}
return null;
}
Finally, you should notice that you can only parse hour values ranging from 1 to 12 with your current format (yyyy-MM-dd hh:mm:ss). If you'd want to parse according to the 24-hour clock, you should use the HH pattern for the hour part instead:
private static final DateFormat FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Your specified format is not matching with data format.
format "yyyy-MM-dd hh:mm:ss" is NOT compatible with data "2015-08-03 09:19:00.000" because of two reason: (1) AM/PM is missing in date as 'hh' takes 1-12 hrs , and (2) milliseconds present in date string
Replace below mentioned line and your issue will be resolved.
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But, none of the above mentioned issue can cause the exception you got as milliseconds is ignored by default.
Possible reasons of exception are return type of method "convertStringToDate" or hh having value beyond the range between01 and 12.
change return type from String to Date
Change date format hh to HH.
It is because you are trying to return a String from your method. Change it to Date.
public static Date convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}
I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?
Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 8 years ago.
How do I get the next date(2014/03/21) given the current date(2014/03/20) in Java?
Code:
public static String getNextDate(String curDate) {
String nextDate="";
try {
//here logic to get nextDate
} catch (Exception e) {
return nextDate;
}
return nextDate;
}
Use SimpleDateFormat to get a Date-object from your string representation, then use Calendar for arithmetics followed by SimpleDateformat to convert the Date-object back to a string representation. (And handle the Exceptions I didn't do)
public static String getNextDate(String curDate) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
final Date date = format.parse(curDate);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
return format.format(calendar.getTime());
}
use java Calendar and you can use to do some date arithmetic such as adding day, months and years
public static String getNextDate(String curDate) {
String nextDate = "";
try {
Calendar today = Calendar.getInstance();
DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = format.parse(curDate);
today.setTime(date);
today.add(Calendar.DAY_OF_YEAR, 1);
nextDate = format.format(today.getTime());
} catch (Exception e) {
return nextDate;
}
return nextDate;
}
You can use Joda Time.
public static String getNextDate(String curDate) {
String nextDate="";
try {
LocalDate date = LocalDate.now();
date = date.plusDays(1);
nextDate = date.toString();
} finally {
return nextDate;
}
}
If you want a more native Java way you could split the string using String.split("/") and then add to the date part. However doing this requires that the carry is handled and that you track leap years.
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);