DynamoDB API documentation tells that a supported date should be a String like:
Date (as ISO8601 millisecond-precision string, shifted to UTC)
How do I get this current Date format in Java?
I saw similar things, but they are not quite exactly:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
Is millisecond precision really necessary?
Hopefully I won't need to add Joda for this.
Need a time stamp, to add it to my Range Primary Key.
Need this to put/insert into the Db.
Using Joda,(planned to avoid it) this code seems to do the trick:
DateTime dt = new DateTime(DateTimeZone.UTC);
DateTimeFormatter fmt = ISODateTimeFormat.basicDateTime();
String str = fmt.print(dt);
//20140710T160939.473Z
Related
I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();
I am getting date in an date object
Date s = ((java.util.Date) ((Object[]) object)[++i]);
i need to set this format 20130509 06:00
so for this I have choosen ..
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(s);
now again my task is to put back in date object that string s1, please advise how to achieve this
Date doesn't have a textual format - or even a time zone or calendar. It's just a number of milliseconds since the unix epoch. There's nothing to set within Date.
You need to differentiate between your fundamental data, and a textual representation of that data - in the same way as the int value 16 is the same as 0x10. I can't think of any time where I've found it appropriate to carry a textual representation of a date around with the date itself. In various places in your program you may well find that you need different representations for the same date - but it's usually the same representation for all dates at that specific part of the program.
As an aside, you should consider using Joda Time instead of java.util.Date - it provides you with a much richer set of types to consider, so you can express what your program is actually dealing with (just a date, just a time, a date/time in a particular time zone etc).
Ideally, you shouldn't try to translate to String format and back again. You should persist the original value and just use the String format for display purpose only.
Otherwise, you can use SimpleDateFormat.parse method.
I recommend using Joda time... how given what you've got you can just do
sdf.parse
#Test
public void testDateStringConversion() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(date);
Date date2 = sdf.parse(s1); // seconds won't match
String s2 = sdf.format(date2);
assertEquals(s1, s2);
}
I searched topics about formatting time but these were all about Date class or DateTime. I am working with Time class. I created time as:
Time time = new Time(Time.getCurrentTimezone()) ;
time.setToNow();
String berkay = time.toString();
System.out.println(berkay);
When I execute it the output is :
20130417T070525GMT(3,106,0,0,1366182325)
actually date and time is correct (2013-04-17 07:05:25)
but I need to convert it into : 20130417070525 (My reason to do this is I will search database according to date so it is easier to compare times in that format)
How can I convert it?
Try this:
Time time = new Time(System.currentTimeMillis()) ;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(time).toString();
System.out.println(date);
EDIT
But as smttsp suggested its much more efficient to store it as timestamp
To convert java.util.Date into String you should consider java.text.SimpleDateFormat.
For using java.util.Date as a parameter of a database query you should pass the Date as is without converting it into any other format.
passing Date parameter to create date range query
<- In the answer there is sample how to create such query.
It is a bit late but if you are working on time and you need to compare or sort, the best way is to use Unix timestamp. It starts from 1-Jan-1970 00:00:00 and increments 1 each second.
It is a long value(64 bit) which is quite efficient to use in both time and space. Here is the website for Unix timestamp conversion.
Also 20130417070525 is 14 char string(at least 15 byte, I guess) and 1366182325 is long(8 byte). So go for long value. U can get it in that way
Date myDate = new Date(); // current time
myDate.getTime(); // converts it to specified format.
I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,
I have seconds like below:
1320130800
I need to convert the value into Date and Time Combination format. While formatting I got the result as follows:
Tuesday,November 1,2011 2:00,AM
But the correct result is as follows:
Tuesday,November 1,2011 7:00,AM
For the above format conversion I used the below code:
long millis = 1320130800*1000;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
Can any one guide me to get the correct answer?
Sounds like it's just a time zone issue - you need to set the time zone for the formatter:
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
(Note that in your sample code, long millis = 1320130800*1000; doesn't work as it performs the multiplication in 32-bit arithmetic; you need something like long millis = 1320130800L*1000;.)
Use the Calendar API instead.
After you have the Date object, construct a Calendar object (getInstance() returns one with the default Time Zone) and do setDate(Date) on it and parse it like that.
Alternatively, you can take a look at Joda Time APIs since they are easy to use.
Regards!