How to remove sub seconds part of Date object - java

java.util.Date gets stored as 2010-09-03 15:33:22.246 when the SQL data type is timestamp, how do I set the sub seconds to zero (e.g. 246 in this case) prior to storing the record.

The simplest way would be something like:
long time = date.getTime();
date.setTime((time / 1000) * 1000);
In other words, clear out the last three digits of the "millis since 1970 UTC".
I believe that will also clear the nanoseconds part if it's a java.sql.Timestamp.

Here is an idea:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("S");
Date d = new Date();
System.out.println(df.format(d));
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
d.setTime(c.getTimeInMillis());
System.out.println(df.format(d));
}

java.util.Calendar can help you.
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.clear(Calendar.SECOND);
date = instance.getTime();

Here is another way by java 8 Instant api
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
or
Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);

Alternatively, you can use Apache Commons DateUtils, for example:
DateUtils.setMilliseconds(new Date(), 0);

Related

How to convert time string value in date format

I am facing issue like I have a datasheet which have a string value like 123459 which is a time and I have another column where I am adding in value as plus 5 seconds.
When I am adding value its add as 123464 instead of 123504.
Could anyone help me to resolve this?
Use the java.time classes built into Java 8 and later. See Oracle Tutorial.
Specifically, the LocalTime and DateTimeFormatter classes.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime localTime = LocalTime.parse("123459", formatter);
LocalTime timeIn5Seconds = localTime.plusSeconds(5);
System.out.println(timeIn5Seconds.format(formatter));
Output
123504
to convert string to date format...
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
to add 5 seconds
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date according to the OBJECT
cal.add(Calendar.SECOND, 5); // adds 5 SECONDS
cal.getTime();

android getDate from milliseconds stored in String field

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-

Using Date instead of Timestamp

My code:
Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
I want to eliminate the use of time stamp in this situation, how can achieve the same thing here with epochTimeStamp without using java.sql.Timestamp? I need the format to be same as if I was using Timestamp.
Since you need a String representation of your Date, then use SimpleDateFormat to convert the Date object into a String:
Calendar calendar = ...
//...
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
System.out.println(sdf.format(date));
System.out.println(sdf.format(epochTimeStamp));
} catch (Exception e) {
//handle it!
}
From your example, prints
01/01/1970 09:21:18
01/01/1970 09:21:18
This gives you the epoch time in the same format as TimeStamp:
public class FormatDate {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS");
LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println(datetime.format(format));
}
}
Another way to represent date time objects in Java is to use the Joda Time libraries.
import org.joda.time.LocalDate;
...
LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00");
//or DateTime startDate = new DateTime ();// creates instance of current time
String formatted =
startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss");
There are several ways to do formatting, setting and getting Time using these libraries that has been more reliable than using the JDK Date and Calendar libraries. These will persist in hibernate/JPA as well. If nothing else, this hopefully gives you options.

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)

How to add 10 minutes to my (String) time?

I have this time:
String myTime = "14:10";
Now I want to add 10 minutes to this time, so that it would be 14:20
How can I achieve this?
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
I would use Joda Time, parse the time as a LocalTime, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
Use Calendar.add(int field,int amount) method.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
You have a plenty of easy approaches within above answers.
This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

Categories

Resources