Is the formatter representation "yyyy-MM-dd HH:mm:ss.sss" is correct way to format the date.
Note that here I've used small 's'(instead of capital 'S') to indicate milliseconds which results wrong time.
If yes what is the difference between yyyy-MM-dd HH:mm:ss.sss and yyyy-MM-dd HH:mm:ss.SSS.
Why some are in small letters and some are in capital letters to indicate the date format.
Here is the sample code which shows the difference
SimpleDateFormat dateFormatLocal = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat dateFormatLocal1 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.sss");
try {
Date d = dateFormatLocal.parse("2015-07-21 11:01:27.063");
Date d1 = dateFormatLocal1.parse("2015-07-21 11:01:27.063");
System.out
.println("------------- Sync Completed in Date -------------"
+ d.getTime());
System.out
.println("------------- Sync Completed in Date -------------"
+ d1.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
//OutPut is
//------------- Date in SSS -------------1437456687063
//------------- Date in sss -------------1437456723000
As you have discovered, the correct pattern for milliseconds is SSS, while sss represents seconds.
They are different capitalization because they represent different parts of the date/time.
In the same way that it would be incorrect to use "yy" four hours, it is incorrect to use "sss" for milliseconds.
Related
I want to format current date in MM/dd/yyyy HH:mm:ss a z format based on locale.
String pattern = "MM/dd/yyyy HH:mm:ss a z";
DateFormat dateFormat = new SimpleDateFormat(pattern, new Locale("ja", "JP"));
Date date = new Date();
System.out.println(dateFormat.format(date));
Output:
04/01/2018 17:15:23 午後 EDT
I want to display EDT in Japanese too. If I try zzzz instead of z in
the pattern, then timezone is localized and displays "Eastern Daylight Time" in Japanese:
String pattern = "MM/dd/yyyy HH:mm:ss a zzzz";
DateFormat dateFormat = new SimpleDateFormat(pattern, new Locale("ja", "JP"));
Date date = new Date();
System.out.println(dateFormat.format(date));
Output:
04/01/2018 17:20:17 午後 東部夏時間
How can we localize the Timezone abbreviation 'EDT' and display in Japanese?
The localized strings are built-in in the JVM, but you can replace them by getting the DateFormatSymbols from the formatter and changing it:
String pattern = "MM/dd/yyyy HH:mm:ss a z";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, new Locale("ja", "JP"));
DateFormatSymbols symbols = dateFormat.getDateFormatSymbols();
String[][] zones = symbols.getZoneStrings();
for (int i = 0; i < zones.length; i++) {
// position 4 is the abbreviation for Daylight Saving Time
String zoneAbbrev = zones[i][4];
// overwrite zone short names (replace EDT with whatever string you want)
if ("EDT".equals(zoneAbbrev)) {
zones[i][2] = "東部夏時間"; // change it to the short name for Standard Time
zones[i][4] = "東部夏時間"; // change it to the short name for Daylight Saving Time
}
}
symbols.setZoneStrings(zones);
dateFormat.setDateFormatSymbols(symbols);
I don't know what should be the correct strings, so I used the same as above, but you can replace them with the correct values: zones[i][2] contains the short name for EST (Standard Time) and zones[i][4] contains the short name for EDT (Daylight Saving Time).
If you're allowed to use external libraries, then please use Apache Commons DateUtils method:
public static Calendar toCalendar(Date date, TimeZone tz)
To create the calendar document from your date and manipulate it after.
I am little bit confused in dates. I am currently working on the weather app and everything works fine .. I just wanna handle this type of format into my own desirable format.
2017-09-10T18:35:00+05:00
I just wanna convert this date into Epoch Time and then I settle the date in my desire format ::
for J-SON
or i wanna convert this date into less figure i.e Sun , 9 september 9:23 Am etc.
http://dataservice.accuweather.com/currentconditions/v1/257072?apikey=JTgPZ8wN9VUy07GaOODeZfZ3sAM12irH&language=en-us&details=true
ThreeTenABP
The other answers are correct, but outdated before they were written. These days I recommend you use the modern Java date and time API known as JSR-310 or java.time. Your date-time string format is ISO 8601, which the modern classes “understand” as their default.
Can you use the modern API on Android yet? Most certainly! The JSR-310 classes have been backported to Android in the ThreeTenABP project. All the details are in this question: How to use ThreeTenABP in Android Project.
long epochTime = OffsetDateTime.parse("2017-09-10T18:35:00+05:00")
.toInstant()
.getEpochSecond();
The result is 1505050500.
Edit: Arvind Kumar Avinash correctly points out in a comment: You do not need to convert an OffsetDateTime to an Instant to get the epoch seconds. You can simply use OffsetDateTime#toEpochSecond.
Example of how to convert this into a human-readable date and time:
String formattedDateTime = Instant.ofEpochSecond(epochTime)
.atZone(ZoneId.of("Africa/Lusaka"))
.format(DateTimeFormatter.ofPattern("EEE, d MMMM h:mm a", Locale.ENGLISH));
This produces Sun, 10 September 3:35 PM. Please provide the correct region and city for the time zone ID you want. If you want to rely on the device’s time zone setting, use ZoneId.systemDefault(). See the documentation of DateTimeFormatter.ofPattern() for the letters you may use in the format pattern string, or use DateTimeFormatter.ofLocalizedDateTime() for one of your locale’s default formats.
Use a SimpleDateFormat instance to parse the string into a Date object:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse("2017-09-10T18:35:00+05:00");
And then use another SimpleDateFormat to display it:
DateFormat format = new SimpleDateFormat("EEE, dd MMMMM h:mm a");
String formatted = format.format(date); // Sun, 10 September 1:35 PM
You can use SimpleDate formatter to parse you date as string into epoch
String input = "2017-09-10T18:35:00+05:00";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = sf.parse(input);
long dateInEpochFormatInMilliSeconds = date.getTime();
//if you want this in seconds then
long dateInEpochFormatInSeconds = date.getTime()/1000L;
//if you want to show only date month and year then
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String date = sdf.format(dateInEpochFormatInMilliSeconds);
//This date String will contain the date in dd-MM-yyyy format
} catch (ParseException| ArithmeticException e) {
e.printStackTrace();
}
String time_at_which_weather_capture = "Time : ";
DateFormat dateFormat = new SimpleDateFormat("EEE,d M yyyy h:MM a");
long timeInMillieSec = 0 ;
try {
Date date = dateFormat.parse(readyToUpdate.getTime());
timeInMillieSec = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
time.setText(time_at_which_weather_capture + String.valueOf(time_fetcher(timeInMillieSec)));
public String time_fetcher (long time_coming_to_its_original_form) {
Date date = new Date (time_coming_to_its_original_form);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d M yyyy h:MM a");
return sdf.format(date);
}
I am using jQuery Datepicker that is giving the date like 07/05/2015 this format.I am using simpledateformat to format this date.But always the SDF is converting it to the todays date.How to solve this ??
System.out.println("Activity IS : IS With Date");
SimpleDateFormat sdfOverTimeWithDate = new SimpleDateFormat("yyyy-MM-dd ");
Date startDate = ParamUtil.getDate(resourceRequest, "startDate", sdfOverTimeWithDate);
Date endDate = ParamUtil.getDate(resourceRequest, "endDate", sdfOverTimeWithDate);
int jobId= ParamUtil.getInteger(resourceRequest, "jobId");
System.out.println("jobId :"+jobId);
System.out.println("startDate :"+startDate);
System.out.println("endDate :"+endDate);
This statDate and endDate is giving todays's date only ,while the date i am pssing is in the format 07/05/2015.How to solve this ??somebody plaese help
You are passing wrong date format to SimpleDateFormat constructor. Try "dd/MM/yyyy" instead of "yyyy-MM-dd "
Is "07/05/2015" in July (US-Format) or May? Please clarify. If it is US-format (date expression starting with month number) then your solution is to use the pattern "MM/dd/yyyy" otherwise you should use the pattern "dd/MM/yyyy".
The pattern "yyyy-MM-dd " cannot be right due to two reasons:
a) It starts with a four-digit-year but your input begins with a two-digit-number.
b) It contains a trailing space.
Try to do it.
SimpleDateFormat sdfOverTimeWithDate = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdfOverTimeWithDate.parse("07/05/2015");
} catch (ParseException e) {
e.printStackTrace();
}
What will be the regular expression for following Timestamp format
YYYY-MM-DD HH:mm:ss.S
YYYY-MM-DD HH:mm:ss.S AM/PM
YYYY-MM-DD HH:mm:ss.S AM/PM Z
YYYY-MM-DD HH:mm:ss.S Z
Where
Y: year,
M: Month,
D: Date,
H: hour,
m: minute,
s: second,
S: Milisecond 3 digit only,
Z: Time zone.
I am getting timestamp format in string format so want to validate it.
How to check above regular expression in GWT?
Just something simple as only describing the pattern like this:
^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}(?: [AP]M)?(?: [+-]\d{4})?$
as any tentative of real date validation with a regex sounds inherently wrong.
I got the uppercase Z as RFC822 timezone, regex needs changes to comply to TZDs or general textual time zones.
Apart from Datejs which relays on js to check a date-string, Gwt comes with DateTimeFormat to parse date-string and format dates with support for locales. It raises a IllegalArgumentException in the case the parsed string doesn't match the expected format .
String dateStr = "2011-04-21 20:37:36.999 -0800";
String fmt = "yyyy-MM-dd HH:mm:ss.S Z"; // your 4th case: YYYY-MM-DD HH:mm:ss.S Z
DateTimeFormat format = DateTimeFormat.getFormat(fmt);
try {
Date date = format.parse(dateStr);
System.out.println("Validated: " + date);
} catch (IllegalArgumentException e) {
System.out.println("Validation error: " + e.getMessage());
}
dateStr = "2011-04-21 08:37:36.999 PM -0800"; // your 3rd case YYYY-MM-DD HH:mm:ss.S AM/PM Z
fmt = "yyyy-MM-dd hh:mm:ss.S a Z";
format = DateTimeFormat.getFormat(fmt);
try {
Date date = format.parse(dateStr);
System.out.println("Validated: " + date);
} catch (IllegalArgumentException e) {
System.out.println("Validation error: " + e.getMessage());
}
You dont say whether the format string is fixed or it can be provided in runtime before performing the validation. So in the second case you need to use replace to change 'Y' by 'y', and 'AM/PM' to 'a' which are the symbols used in DateTimeFormat
I would say use Datejs
Otherwise you will need to do a lot of coding, and regex is not the best for verifying timestamps and if it is valid.
Datejs will check the date validity, and from that you will receive a Date object or null (if it is invalid!).
Date.parse("2013-02-02 12:01:01.000", "yyyy-MM-dd HH:mm:ss.u");
For more information see:
Datejs API documentation
Datejs Format spec
How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());