How to convert a string Date to long millseconds - java

I have a date inside a string, something like "12-December-2012".
How can I convert this into milliseconds (long)?

Using SimpleDateFormat
String string_date = "12-December-2012";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date d = f.parse(string_date);
long milliseconds = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}

It’s about time someone provides the modern answer to this question. In 2012 when the question was asked, the answers also posted back then were good answers. Why the answers posted in 2016 also use the then long outdated classes SimpleDateFormat and Date is a bit more of a mystery to me. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with. You can use it on Android through the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.
For most purposes I recommend using the milliseconds since the epoch at the start of the day in UTC. To obtain these:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
String stringDate = "12-December-2012";
long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
System.out.println(millisecondsSinceEpoch);
This prints:
1355270400000
If you require the time at start of day in some specific time zone, specify that time zone instead of UTC, for example:
.atStartOfDay(ZoneId.of("Asia/Karachi"))
As expected this gives a slightly different result:
1355252400000
Another point to note, remember to supply a locale to your DateTimeFormatter. I took December to be English, there are other languages where that month is called the same, so please choose the proper locale yourself. If you didn’t provide a locale, the formatter would use the JVM’s locale setting, which may work in many cases, and then unexpectedly fail one day when you run your app on a device with a different locale setting.

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();

Take a look to SimpleDateFormat class that can parse a String and return a Date and the getTime method of Date class.

First convert string to java.util.Date using date formatter
Use getTime() to obtain count of millisecs from date

you can use the simpleDateFormat to parse the string date.

Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)

using simpledateformat you can easily achieve it.
1) First convert string to java.Date using simpledateformatter.
2) Use getTime method to obtain count of millisecs from date
public class test {
public static void main(String[] args) {
String currentDate = "01-March-2016";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date parseDate = f.parse(currentDate);
long milliseconds = parseDate.getTime();
}
}
more Example click here

Try below code
SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
Date d = null;
try {
d = f.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
long timeInMillis = d.getTime();

Related

String date into Epoch time

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);
}

Convert yyyy-MM-dd'T'HH:mm:ss.mmm'Z' to normal "HH:mm a" format

I have a problem in displaying the date in my Application.
I am getting timestamp as:
2017-08-02T06:05:30.000Z
But as per this the actual time is:
2017:08:02 11:35 AM
But after converting using my code it displays the time as:
6:00 am
How to show it as current time?
My code is given below:
private static SimpleDateFormat timestampformat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");
private static SimpleDateFormat sdftimeformat = new SimpleDateFormat("HH:mm a");
private static SimpleDateFormat getSdftimeformat() {
return sdftimeformat;
}
public static String timeStampConvertToTime(String time) {
Date date1 = null;
try {
date1 = timestampformat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = getSdftimeformat().format(date1);
return formattedTime;
}
The first thing is that you're using mm:ss.mmm in your format. According to SimpleDateFormat javadoc, m represents the minutes, so you must change it to mm:ss.SSS because S represents the milliseconds.
Another detail is that the Z in the end is the timezone designator for UTC and it can't be ignored (at least it shouldn't). You must use the corresponding pattern for that, which is X:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
PS: the X pattern was introduced in Java 7. If you're using Java <= 6, the only alternative is to treat Z as a literal (an ugly workaround, I admit) and set the UTC as the timezone used by the parser:
// treat "Z" as literal
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
With this, the date will have the value corresponding to 06:05 in UTC. To format the time to your timezone, you must use another SimpleDateFormat with the corresponding timezone:
// output format: hour:minute AM/PM
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
// assuming a timezone in India
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(date));
The output will be:
11:35 AM
If you don't set a timezone, it'll use the system's default. But the default can be changed without notice, even at runtime, so it's better to explicity set a specific timezone as above.
I also used java.util.Locale to set the language to English, because some locales can have different symbols for AM/PM. If you don't specify one, it'll use the system default and it's not guaranteed to be one in which the symbols are the ones you need (some locales uses "a.m./p.m." or another different formats, so it's better to use an explicit locale).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse the input you can use the ZonedDateTime class, which has full support to timezones and it makes the conversion to another zones very easy. Then you use a DateTimeFormatter to format the output:
// parse the input
ZonedDateTime parsed = ZonedDateTime.parse("2017-08-02T06:05:30.000Z");
// convert to another timezone
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
// format output
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output will be:
11:35 AM
If the input always has Z in the end, you can also use the Instant class:
// parse the input
Instant instant = Instant.parse("2017-08-02T06:05:30.000Z");
// convert to a timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Asia/Kolkata"));
Note that I used hh for the hours: this will format using values from 1 to 12 (it makes sense because I'm also using the AM/PM designators). If you want values from 0 to 23, use HH instead - check the javadoc for more details.
Also note that the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or IST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use the system's default timezone with ZoneId.systemDefault(), but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.
You need to use SimpleDateFormat class and specify the format you want to parse from , like this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
long timeStamp = sdf.parse('your_timestamp').getTime();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.getDefault());
String time =currentDateFormat.format(timeStamp); // Formatted time in string form
try this your will get result
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
// set your format in df variable
SimpleDateFormat df = new SimpleDateFormat(
"HH:mm a");
try {
cal.setTime('your value');
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String localtime = df.format(cal.getTime());
use this for get current time.
Calendar cal =
Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm a");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
String localTime = date.format(currentLocalTime);
change time zone to your time zone
I assume the Z in Rose's timestamp is zulu time, it isn't really correct to hard code the conversion from zulu time to his local time zone (GMT+5:30 we are assuming). It might be OK if it is always returning Z but if it is
military time zones you would need something that can handle all the possible timezones.
This previous question implies there is no built in way to do it. Need to understand where the timestamp is coming from to really answer the question.

How to format time including milliseconds

I'm trying to get a time string in the format of YYYYMMDD-HHMMSSMilliseconds in Android
Ex: 20130312-1723437520 (2013 March 12th, 17 Hour 23 Minutes 43 Seconds 7520 Milliseconds)
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("yyyyMMdd-HHmmss");
First of all, above code doesn't even work properly. snapshotTime is always set to the format string itself.
Second of all, according to the Android documentation, there's no way to record milliseconds.
How can I accomplish this?
See the SimpleDateFormat class, you can format a Date object into the required format (upper-case S will give millis)
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String str = fmt.format(now);
That said, using Joda Time is usually a good idea (Proguard will strip code you don't use).
You'll have to use the strftime formatting, as noted in the Android docs.
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("%Y%m%d-%H%M%S");
If you really want to use milliseconds than I would recommend SimpleDateFormat.
Try getting the time as unix timestamp with milliseconds from
long currentTime = System.currentTimeMillis();
or convert your time to milliseconds:
long currentTime = now.toMillis(true);
Then you can convert this to your desired date:
Time now = new Time();
now.set(currentTime);
String snapshotTime = now.format("%Y%m%d-%H%M%S")+""+(currentTime%1000);
Didn't test it but hope it works :)
I would recommend to use this little library, it's very helpful when working with dates. Have a look at the DateTimeFormatter class.
As an alternative use Calendar and SimpleDateFormater (you'll have to adjust the format string of course, see this for explanation of the symbols)
Calendar c = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-SSSS");
String date = sdf.format(c.getTime());
You can try this:
public static String format() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
Date now = new Date();
return simpleDateFormat.format(now);
}

Converting Epoch time to date string

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)

Removing time from a Date object?

I want to remove time from Date object.
DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format
But when I'm converting this date (which is in String format) it is appending time also.
I don't want time at all. What I want is simply "21/03/2012".
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
The quick answer is :
No, you are not allowed to do that. Because that is what Date use for.
From javadoc of Date :
The class Date represents a specific instant in time, with millisecond precision.
However, since this class is simply a data object. It dose not care about how we describe it.
When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need.
There are many ways to do this.
Example 1 : by manipulating string
Input string : 2012/01/20 12:05:10.321
Desired output string : 2012/01/20
Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.
String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10); // Output : 2012/01/20
Example 2 : by SimpleDateFormat
Input string : 2012/01/20 12:05:10.321
Desired output string : 01/20/2012
In this case we want a different format.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012
For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.
Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:
DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);
DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.
What about this:
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = sdf.parse(sdf.format(today));
What you want is impossible.
A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.
edit - note that my answer above is now more than 10 years old. If you are using a current version of Java (Java 8 or newer), then prefer to use the new standard date and time classes in package java.time. There are many classes available that represent just a date (day, month, year); a date and time; just a time; etc.
Date dateWithoutTime =
new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate())
This is deprecated, but the fastest way to do it.
May be the below code may help people who are looking for zeroHour of the day :
Date todayDate = new Date();
GregorianCalendar todayDate_G = new GregorianCalendar();
gcd.setTime(currentDate);
int _Day = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
int _Month = todayDate_GC.get(GregorianCalendar.MONTH);
int _Year = todayDate_GC.get(GregorianCalendar.YEAR);
GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
zeroHourDate = newDate.getTime();
long zeroHourDateTime = newDate.getTimeInMillis();
Hope this will be helpful.
you could try something like this:
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
String s;
Format formatter;
Date date = new Date();
formatter = new SimpleDateFormat("dd/MM/yyyy");
s = formatter.format(date);
System.out.println(s);
}
}
This will give you output as21/03/2012
Or you could try this if you want the output as 21 Mar, 2012
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
Date date=new Date();
String df=DateFormat.getDateInstance().format(date);
System.out.println(df);
}
}
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.
So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("en-IE"));
LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
String dateString = d.format(dateFormatter);
System.out.println(dateString);
Example output:
21/03/2012
If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):
d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
LocalDate dateWithoutTime = d.toInstant()
.atZone(ZoneId.of("Asia/Kolkata"))
.toLocalDate();
Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.
The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).
Link: Oracle tutorial: Date Time explaining how to use java.time.
A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is " + df.format(d));
gives
date is 2011-12-05
formatted date is 05/12/2011
Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.
java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).
What you might want is a java.sql.Date to represent only the date portion (though internally it still uses ms).
String substring(int startIndex, int endIndex)
In other words you know your string will be 10 characers long so you would do:
FinalDate = date.substring(0,9);
Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp.
Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).
In addtition to what #jseals has already said. I think the org.apache.commons.lang.time.DateUtils class is probably what you should be looking at.
It's method : truncate(Date date,int field) worked very well for me.
JavaDocs : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)
Since you needed to truncate all the time fields you can use :
DateUtils.truncate(new Date(),Calendar.DAY_OF_MONTH)
If you are using Java 8+, use java.time.LocalDate type instead.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml.
eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
Don't try to make it hard just follow a simple way
date is a string where your date is saved
String s2=date.substring(0,date.length()-11);
now print the value of s2.
it will reduce your string length and you will get only date part.
Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.
#SuppressWarnings("deprecation")
...
Date hitDate = new Date();
hitDate.setHours(0);
hitDate.setMinutes(0);
hitDate.setSeconds(0);

Categories

Resources