I use the below code to format date time in iso format using java (I'm reducing 1 min from current time) and get the output as this "2016-03-17T11:38:21.xxxZ" < x represent some numbers> i want this to compare with the time which have mentioned in the DB.
Person who build that data insert query, he used javascript to get the time and format it in iso.
Date inside the DB is looks like this "2016-03-17T06:09:21.530Z" and its actual time is "11:39:21 GMT+0530 (India Standard Time)" which is similar to my current time but I'm comparing these two dates as string. and get 1min early data from DB.In that case i can't get an out put because as strings these two aren't match. can anybody recomand a solusion ?
I use OrientDB
Java Code
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
date.setTimeInMillis(t);
date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) - 1);
String time1minEarly = df.format(date.getTime());
Using Calendar.set() and Calendar.get() does not modify the date in a way you intend:
This will modify the minutes field in your case. So subtracting "1" will reduce the minute but not give a viable date for cases where minute initially is zero.
You may just subtract a minutes of milliseconds from your "t" variable to get a true minute offset.
And for ease of use you might also consider following advise from #Prashant and using LocalDateTime class from joda library.
Thanks Everybody for your support.
I figure out How to do this. it's pretty easy. Both #rpy and #Prashant are correct. Calendar is not suitable for solve my issue. Also LocalDateTime too. but it did help me to figure out the correct way.
#rpy and #Prashant they both did miss one thing that the javascript time represent the UTC time. that's the issue. (it's 5.5 hours behind compared to my location) so, I figure out this below code. it did what i wanted to do.
It's pretty easy. all you have to do is provide your zone id.
(You can get Zone id using this code : go to the link - http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)
Also you can choose so many formats by changing "DateTimeFormatter" value.
ZoneId UTCzoneId = ZoneId.of("UTC");
ZonedDateTime time1minEarly = ZonedDateTime.now(UTCzoneId).minusMinutes(1);
String UTCtime1minerly = time1minEarly.format(DateTimeFormatter.ISO_INSTANT);
Out put is similar to this : "2016-03-17T10:39:21.530Z"
(- UTC time at that time : 2016-03-17T10:40:21.530Z)
Related
I've a list of timespan(object list actually), like 2:00, 15:00, 18:00 etc, it is in utc.
Now i want to convert this time slot back to CST and then sort it, as i want my time sorted in cst.
For timezone conversion i needed temporary date. so i choose current utc date by
moment.utc(mytimespan). and performed the timezone conversion by .tz("CST").
So list is converted to 20:00,9:00, 12:00
Here please note that i got 20:00 in first place instead of last place in the list.
This is due to date part of moment which went in back date.
All here i want is my timespan in sorted form without any effect of date.
please me to find a way to do it without string conversion!
Thanks
Update
my currently working code using string conversion
TimeSpanDetails.sort(function compare(a, b) {
return moment(moment.utc(a.startTime).tz("CST").format("HH:mm"),"HH:mm").isAfter(moment(moment.utc(b.startTime).tz("CST").format("HH:mm"),"HH:mm")) ? 1 : -1;
});
Now i want to do it without string conversion using format
A few things:
A "time span" usually refers to a duration of time, not a time-of-day. These are two very different concepts that are sometimes confused. Consider:
A timespan of 99 hours is perfectly valid, but "99:00" is nonsensical as a time-of-day.
Due to daylight saving time and other time zone transitions, a timespan can't necessarily be thought of as "time since midnight" because midnight may or may not exist, or some other hour of the day may be absent or repeated.
Time spans can be negative in some programing languages, usually representing a period before a given point in time.
The tz function in Moment.js takes IANA time zone names. You should not use CT or CST, but rather America/Chicago, for example. However, time zones are completely unrelated to time spans, so you should not be applying them at all. You do not need moment-timezone.
Moment represents time spans in Duration objects. You can parse them from strings like so:
var d = moment.duration('99:00');
Duration objects convert numerically to milliseconds, so they are comparable like so:
var a = moment.duration('00:00');
var b = moment.duration('01:00');
var c = a < b; //=> true
Moment does not have a strongly typed object for a time-of-day, but you can use Moment in UTC mode so that it does not have DST transitions, and then just let it use the current day. HOWEVER:
This would assume that all time-of-day values you have should be evaluated on the same date.
This may or may not be the case.
Consider that if all you have is time-of-day and don't know what dates they're from, then the values ['23:00', '00:00'] may be sorted already and only one hour apart, or perhaps they're out of sequence and they are 23 hours apart.
Similar questions has been asked many times but I couldn't find a more concrete solution. The things I'm doing are:
I have a <input type="date"> inside my HTML which when clicked opens a calender with date in dd/mm/yyyy format.
I change the html5 date to timestamp to send to my db by Date.parse(html5Date) and in the server I modify the date and send it back to my Angular app.
I now convert the timestamp back to Date object by new Date(timestamp).To print the date in a human-friendly format inside a table I do [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/').
On edit (PUT request), I again capture the date from HTML, convert it to timestamp, send it to server and process the returning date back to html date.
Other than these, I also do a ton of functionalities like date comparison, adding hours to the dates, show time of the day etc inside the HTML:
Just these simple operations are over 120 lines of code which I think is ridiculous and error prone. I've looked into Angular Datepicker but it's a bit confusing. Also sometimes the HTML date is of type Object and sometimes it's String so Date.parse() gives error.
Are there any developer friendly methods that does : copy HTML5 date (from datepicker) --> change to timestamp (for angular&server) --> format timestamp back to string/object (for html)? Thank You :)
Note: Angular throws a lot of annoying error in console saying dateformat is wrong (being html date type) but doesn't stop code from running
Sounds like you are doing waaay to many conversions. I would argue that there should only be one way dates are represented: as Date objects in the programming language. There are only a few conversions that need to happen:
Date <=> Integer milliseconds since the epoch to pass to server
Date <=> String human-readable format to display to user
Any thing beyond this is asking for trouble. Comparisons can be made by casting to int date.getTime(), comparing, and casting back to Date. Ditto for additions. Note that Date.parse is implementation dependent in what it will accept, although all of them will accept ISO 8601 formatted date strings anything else is guesswork. Which means you will have to deal with converting strings by hand, something like the following:
var toDate = str => {
var splitter = str.indexOf("/") === -1 ? "-" : "/";
var [mon, day, year] = str.split(splitter);
return new Date(year, mon - 1, day);
};
var toDateString = date => {
return "" + date.getFullYear() + (date.getMonth() + 1) +...
};
Note that there's no validation, that's left as an exercise to the reader.
A WORD ABOUT MOMENT.JS
moment.js is awesome. Its also huge, its a kitchen-sink API with a heft to match. You're already loading angular, so think carefully before bulking the size of your payload with another huge library.
Moment.js is a powerful date formatting and manipulation library. A lot of things you can do in Moment.js are a single line of code, which makes life a lot easier. I agree, without using a library like this date formatting and handling can be a pain.
http://momentjs.com/
EDIT: fyi, I use this with my Angular app and find it extremely useful!
My service is returning this as date 7/14/2016 2:40 AM +00:00. How can I convert this to UTC in JS?
Tried:
new Date("7/14/2016 2:40 AM +00:00").toISOString();
In database the date has been stored as UTC so when I will display the date I want to display as Local time.
There are many ways to parse a string to produce a Date object.
One way is with the Date object itself, either by passing a string to the constructor, or by using Date.parse. However, only the ISO8601 formats are required in the ECMAScript specification. Any other input is implementation specific, and may or may not be recognized by the different JavaScript runtimes. With web browsers in particular, there are many differences in supported formats across browsers.
Additionally, the locale of the environment plays a factor in how the values are parsed. How should 1/2/2016 be parsed? January 2nd, or February 1st? You showed an example of 7/14/2016, which would be invalid input if ran in the UK (for example), where the date format is DD/MM/YYYY.
You can write custom code to split the string up into its parts, parse each part individually, and compose a result. The main problem with this approach is that the code tends to be rigid, and sometimes fragile. It should be well tested, and many edge cases need to be considered.
You can use a library, which is by far the easiest and most flexible approach (IMHO). With a good library, you can take comfort in the shared experiences of others, and in the unit tests that are (hopefully) part of the library you choose. Of course, using a library comes with several tradeoffs including increased file size, and relinquishing some degree of control. You should evaluate these tradeoffs carefully.
There are many date libraries available for JavaScript. The most popular is probably moment.js, though there are others to choose from, and some larger frameworks sometimes have similar functionality already included.
Here is an example using moment.js:
var i = "7/14/2016 2:40 AM +00:00";
var f = "M/D/YYYY h:mm A Z";
var m = moment(i, f);
var o = m.format(f); // will be in the local time, in the same format as the input
var d = m.toDate(); // if you really want a Date object
Assuming you can guarantee that format for all dates, the following code will suffice:
const datetime = '7/14/2016 2:40 PM +00:00'; // this is what your service returns
const pieces = datetime.split(/[/: ]/);
if (pieces[3] == 12) pieces[3] = 0; // fixes edge case for 12 AM/PM
const hours = pieces[5] === 'PM' ? Number(pieces[3]) + 12 : pieces[3];
const d = new Date(Date.UTC(pieces[2], pieces[0] - 1, pieces[1], hours, pieces[4]));
console.log(datetime); // prints "7/14/2016 2:40 PM +00:00"
console.log(d); // prints Date 2016-07-14T14:40:00.000Z
EDIT: There's a couple edge cases with this not handled correctly, namely 12 AM/PM, etc. but those can easily be worked around as well.
EDIT2: Accounted for that edge case.
EDIT3: As a comment stated, this will only work for UTC times. If the string you're receiving can have any offset, this will not work.
var str = "7\/15\/2016 1:00 AM +00:00".replace("+00:00","UTC");
console.log(new Date(str).toISOString()); // 2016-07-15T01:00:00.000Z
I'm trying to get difference of days between two GMT dates using moment
but I couldn't find it.
I'm on IST(+05:30) and I have some GMT dates(-05:00) in db,
I tried using following command
temp2.diff(temp1, "days")
here is a screenshot of all the commands tried in console
there we can clears see that dates are different and still shows the difference is 0
here is how I'm initializing moment objects of 'America/New_York'
var temp1 = moment.tz(new Date('Mon Jan 25 2016 22:00:00 GMT-0600'), 'America/New_York');
var temp2 = moment.tz(new Date('Tue Jan 26 2016 00:00:00 GMT-0600'), 'America/New_York');
any help appreaciated, thanks.
Well, there is less than 24 hours difference between those dates, so it's correct. The documentation says:
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument.
> temp2.diff(temp1, "days", true)
0.08333333333333333
If you don't care about the hours at all, set them to 0 before you do the comparison
> temp2.hours(0).diff(temp1.hours(0), "days")
1
A few things:
You say that you are retrieving these values from a database, but then you show us loading them via the Date constructor from a string value. If you are really storing a string in your database, especially in that particular format, then you have much larger problems than the one you asked about! Please show us precisely how you load the values from your database to begin with.
You shouldn't rely on the Date object for parsing, especially when you are already using moment, which has much better parsing routines of its own.
You said these values where in America/New_York, but then you show an offset of -0600. That's never used in that time zone. The offset for the value you showed would be -0500.
You also said "I have some GMT dates(-05:00)" - which doesn't make any sense. GMT is +00:00. GMT-0500 means "5 hours behind GMT". Thus, you no longer have a "GMT date".
Be aware that the JavaScript Date object can only use the time zone of where the code is running. You cannot run it in any other time zone.
While Felix is correct in how you can show decimals with the diff function, you should realize that diff is giving you the actual elapsed time between the two moments in time you asked about. However, you seem to be wanting to know the total number of calendar days separating the two days that the moments fall into within the named time zone. To do that, you'd need to ignore the time portion. Using startOf('day') is an easy way to do that. Consider:
var a = moment.parseZone("2016-01-25T23:00:00-05:00");
var b = moment.parseZone("2016-01-26T01:00:00-05:00");
b.diff(a, 'days', true) // 0.08333333333333333 (not what you want)
b.startOf('day').diff(a.startOf('day'), 'days') // 1 (that's better!)
moment(b).startOf('day').diff(moment(a).startOf('day'),'days') // 1 (best approach)
Note a few things with this code:
The code in the last line is the best approach, as it leaves the original values of a and b alone. Otherwise, they would be modified. (Moments are mutable.)
You seem to already have the correct local time and offset, and thus there's no need to use moment-timezone's tz function. You can just use parseZone. Of course if this was just a side effect of your example, then you could still use moment-timezone, but I'd strongly recommend against using the Date constructor still.
I want to convert javascript time stamps to erlang dates. I am using the qdate library to help me do that since it also provides functions for date arithmetic.
Calling it's to_date function first before midnight and then after midnight results in time displacement of 24 hrs. For example:-
qdate:to_date(Timestamp div 1000).
%% {2015,5,2} before midnight
qdate:to_date(After_midnight_Timestamp div 1000)
%%{2015,5,2} after midnight should be 3 instead of 2
I googled around a bit and found this in the erlang calender docs
The time functions local_time/0 and universal_time/0 provided in this module both return date and time. The reason for this is that separate functions for date and time may result in a date/time combination which is displaced by 24 hours. This happens if one of the functions is called before midnight, and the other after midnight. This problem also applies to the Erlang BIFs date/0 and time/0, and their use is strongly discouraged if a reliable date/time stamp is required.
I am having trouble understanding this. Which one of the functions from local_time/0 and universal_time/0 always gives the correct results? By correct I mean I want the right date to be shown after midnight. The resolution of the time is only {y,m,d}. Don't care for hours, minutes and seconds or anything finer than that.
So how do I reliably convert a javascript timestamp to a date in erlang?
Looks like it was just a timezone issue :) Since I was working with javascript timestamps the default timezone of the javscript time stamp is my localtimzone which is "IST". Now internally when qdate sees an integer in qdate:to_date(Timestamp). it automatically selects a UTC timezone for it. Relevant code on line 256:-
raw_to_date(Unixtime) when is_integer(Unixtime) ->
unixtime_to_date(Unixtime);
%% other clauses
and on line 654
unixtime_to_now(T) when is_integer(T) ->
MegaSec = floor(T/1000000),
Secs = T - MegaSec*1000000,
{MegaSec,Secs,0}.
unixtime_to_date(T) ->
Now = unixtime_to_now(T),
calendar:now_to_datetime(Now).
The final clue comes from the erlang calendar documentation itself
now_to_datetime(Now) -> datetime1970()
Types: Now = erlang:timestamp()
This function returns Universal Coordinated Time (UTC) converted from the return value from erlang:now().
So the solution to this problem was to simply supply an IST string with qdate:to_date() like so:-
qdate:to_date("IST",Timestamp div 1000)
and it started returning correct dates. I wasn't sure of the solution so I ran a test with qdate:to_date(erlang:now()) and the value returned was exactly 5:30 hrs behind my clock time. So it seems that supplying the timezone string works :)