How to convert '20211114025320+0000' to JS date object - javascript

I need to convert string: '20211114025320+0000' to JS Date object
(2021-11-14T02:53:20.000Z).
I have this format for info ('YYYYMMDDHHmmssZ')
maybe I need to use a custom function for this?

It looks like what you have is an ISO 8601 string with all the separators stripped away.
Therefore, a straight-forward way would be to add these separators back using a regex replace and then parsing it using the built-in parser:
function parseCustomDate (s) {
const isoString = s.replace(/^(....)(..)(..)(..)(..)(.*)$/, '$1-$2-$3T$4:$5:$6')
return new Date(isoString)
}
(Note that here the last capture group with the .* captures both seconds and the timezone specifier at once, because those don't need a separator between them anyway. To make it clearer, you could also use (..)(.*) and $6$7 instead of only (.*) and $6 as I did.)
Another way that is faster computationally but also more complex to read, understand and catch bugs in (in my opinion at least) would be to take the individual parts of the string and pass them to the Date.UTC constructor instead of going through the ISO string route:
function parseCustomDate (s) {
const year = Number(s.slice(0, 4))
const month = Number(s.slice(4, 6))
const day = Number(s.slice(6, 8))
const hour = Number(s.slice(8, 10))
const minute = Number(s.slice(10, 12))
const second = Number(s.slice(12, 14))
const tzSign = s.slice(14, 15)
const tzHour = Number(tzSign + s.slice(15, 17)) || 0
const tzMinute = Number(tzSign + s.slice(17, 19)) || 0
return new Date(Date.UTC(
year, month - 1, day,
hour - tzHour, minute - tzMinute, second
))
}
Explanation for the timezone handling here: JavaScript accepts "invalid" dates that have individual parts outside of the regular range by rolling them over, so e.g. 11:70:00 would become 12:10:00. This is why we can simply subtract the timezone parts (with each part also capturing the +/- sign), and we don't even have to mess with multiplying the minutes by 60 because we can handle them in the minutes part too.
I added the || 0 so that a string with a Z as timezone which would otherwise make tzHour and tzMinute NaN would also be handled as zero timezone offset.

A function to parse the string and pass the parts directly the Date constructor may be more efficient than parsing the string to generate another string that is then parsed by the built–in parser.
This method also avoids the built–in parser, which is usually considered a good idea.
// Parse YYYYMMDDHHmmss±HHmm or YYYYMMDDHHmmssZ
function parseTS(ts) {
// Get parts
let [C,Y,M,D,H,m,s,sign,oH,oM] = ts.match(/\d\d|\D/g);
// Deal with offset: ±HHmm or Z
if (sign == 'Z') {
sign = oH = oM = 0;
}
let oSign = sign == '+' ? -1 : +1;
// Create date from parts, adjust H, m for offset
return new Date(Date.UTC(C+Y, M-1, D, +H + oH*oSign, +m + oM*oSign, s));
}
['20211114082320+0530',
'20211114025320+0000',
'20211114025320Z',
'20211113225320-0400'
].forEach(ts => console.log(ts + '\n' + parseTS(ts).toISOString()));

Related

determine if a timestamp in this format is within a particular range in JavaScript

I have a bunch of timestamps that have the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.
I am trying to write a function to determine if a given timestamp is within a range:
function isBetween(start, end, toCompare) {
}
for example, isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59") should return true as "2017:01:01:23:59:59" is between '2017:01:01:23:59:58' and "2017:01:02:23:59:58"
I couldn't find a clean way to do it. Can someone help me with this?
In JavaScript, Date objects can be compared fairly easily. However, as you've probably noticed, the format of the string you provided is not a format that can be parsed by JavaScript's Date object, so we will first have to fix that. Fortunately, this format is extremely predictable.
The first thing I notice is that the "Month" and "Date" are preceded by a zero if they're a single digit. This means that the date portion is always the exact same amount of characters (10). Because this is the case, we can use String.prototype.substring() to get the first 10 characters for the date, and get everything after the 11th character to get the time while skipping the colon in the middle.
var datetime = "2017:01:01:23:59:58";
var date = datetime.substring(0, 10);
var time = datetime.substring(11);
console.log("Date: " + date);
console.log("Time: " + time);
Now that they're separate, all we need to do is replace the colons in the date with forward slashes, then concatenate it with the time separated by a space. After this, we will have a date string in the MM/dd/yyyy hh:mm:ss format, which we can then parse using JavaScript's built in Date class.
var input = "2017:01:01:23:59:58";
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
console.log(new Date(datetime));
Now we can throw this into it's own function, then use simple comparison to figure out if toCompare is between start and end.
function isBetween(start, end, toCompare) {
var startDate = convertDate(start);
var endDate = convertDate(end);
var compareDate = convertDate(toCompare);
return compareDate > startDate &&
compareDate < endDate
}
function convertDate(input){
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
return new Date(datetime);
}
var between = isBetween("2017:01:01:23:59:58", "2017:01:02:23:59:58", "2017:01:01:23:59:59");
console.log(between)
This could work for you:
function isBetween(start, end, toCompare) {
start = dateGenerator(start)
end = dateGenerator(end)
toCompare = dateGenerator(toCompare)
if(start <= toCompare && toCompare <= end) return true
return false
}
function dateGenerator(str) {
str = str.split(":")
let date = new Date(`${str[0]}-${str[1]}-${str[2]}`)
date.setHours(str[3],str[4],str[5])
return date.valueOf()
}
const truthy = isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59")
console.log(truthy)
Firstly get individual values and add accordingly to Date constructor of JS and set the hours accordingly.
For comparison we can convert this unix figures (valueOf), hence it will be easier to compare.
This may seem as complex approach but it works.

How to reposition datetime into the current timezone when converting an ISO 8601 datetime string to a **Date** object?

Let's say we're in London at midnight on 2020-01-01 and make an entry into an app that stores the datetime as an ISO-8601 string like this.
2020-01-01T00:00:00-00:00
Later, I am in Los Angeles and want to view this date on a chart that requires a javascript date object.
Getting the localized date object is easy.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theDate = new Date(iso8601Date);
console.log(typeOf(theDate)); // date
console.log(theDate); // Tue Dec 31 2019 16:00:00 GMT-0800 (PST)
But, sometimes we want to "ignore" the timezone offset and analyze the data as if it happened in the current timezone.
This is the result I'm looking for but don't know how to accomplish.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theRepositionedDate = someMagic(iso8601Date);
console.log(typeOf(theRepositionedDate)); // date
console.log(theRepositionedDate); // Wed Jan 01 2020 00:00:00 GMT-0800 (PST)
How do you reposition the date and return a date object?
/* Helper function
Returns the object type
https://stackoverflow.com/a/28475133/25197
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
*/
function typeOf(obj) {
return {}.toString
.call(obj)
.split(' ')[1]
.slice(0, -1)
.toLowerCase();
}
This is really a duplicate of Why does Date.parse give incorrect results?, but that may not seem apparent at first glance.
The first rule of parsing timestamps is "do not use the built–in parser", even for the 2 or 3 formats supported by ECMA-262.
To reliably parse a timestamp, you must know the format. Built–in parsers try and work it out, so there are differences between them that may well produce unexpected results. It just happens that '2020-01-01T00:00:00+00:00' is probably the only supported format that is actually reliably parsed. But it does differ slightly from strict ISO 8601, and different browsers differ in how strictly they apply the ECMAScript parsing rules so again, very easy to get wrong.
You can convert it to a "local" timestamp by just trimming the offset information, i.e. '2020-01-01T00:00:00', however Safari at least gets it wrong and treats it as UTC anyway. ECMAScrip itself is inconsistent with ISO 8601 by treating date–only forms of ISO 8601 as UTC (i.e. '2020-01-01' as UTC when ISO 8601 says to treat it as local).
So just write your own parser or use a library, there are plenty to choose from. If you're only looking for parsing and formatting, there are some that are less than 2k minified (and there are examples on SO).
Writing your own is not that challenging if you just want to support straight forward ISO 8601 like formats, e.g.
// Parse ISO 8601 timestamps in YYYY-MM-DDTHH:mm:ss±HH:mm format
// Optional "T" date time separator and
// Optional ":" offset hour minute separator
function parseIso(s, local) {
let offset = (s.match(/[+-]\d\d:?\d\d$/) || [])[0];
let b = s.split(/\D/g);
// By default create a "local" date
let d = new Date(
b[0],
b[1]-1,
b[2] || 1,
b[3] || 0,
b[4] || 0,
b[5] || 0
);
// Use offset if present and not told to ignore it
if (offset && !local){
let sign = /^\+/.test(offset)? 1 : -1;
let [h, m] = offset.match(/\d\d/g);
d.setMinutes(d.getMinutes() - sign * (h*60 + m*1) - d.getTimezoneOffset());
}
return d;
}
// Samples
['2020-01-01T00:00:00+00:00', // UTC, ISO 8601 standard
'2020-01-01 00:00:00+05:30', // IST, missing T
'2020-01-01T00:00:00-0400', // US EST, missing T and :
'2020-01-01 00:00:00', // No timezone, local always
'2020-01-01' // Date-only as local (differs from ECMA-262)
].forEach(s => {
console.log(s);
console.log('Using offset\n' + parseIso(s).toString());
console.log('Ignoring offset\n' + parseIso(s, true).toString());
});
Building off of #RobG's answer I was able to speed this one up a little by using a single regex. Posting here for posterity.
const isoToDate = (iso8601, ignoreTimezone = false) => {
// Differences from default `new Date()` are...
// - Returns a local datetime for all without-timezone inputs, including date-only strings.
// - ignoreTimezone processes datetimes-with-timezones as if they are without-timezones.
// - Accurate across all mobile browsers. https://stackoverflow.com/a/61242262/25197
const dateTimeParts = iso8601.match(
/(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:([+-])(\d{2}):(\d{2}))?)?/,
);
// Create a "localized" Date by always specifying a time. If you create a date without specifying
// time a date set at midnight in UTC Zulu is returned. https://www.diigo.com/0hc3eb
const date = new Date(
dateTimeParts[1], // year
dateTimeParts[2] - 1, // month (0-indexed)
dateTimeParts[3] || 1, // day
dateTimeParts[4] || 0, // hours
dateTimeParts[5] || 0, // minutes
dateTimeParts[6] || 0, // seconds
dateTimeParts[7] || 0, // milliseconds
);
const sign = dateTimeParts[8];
if (sign && ignoreTimezone === false) {
const direction = sign === '+' ? 1 : -1;
const hoursOffset = dateTimeParts[9] || 0;
const minutesOffset = dateTimeParts[10] || 0;
const offset = direction * (hoursOffset * 60 + minutesOffset * 1);
date.setMinutes(date.getMinutes() - offset - date.getTimezoneOffset());
}
return date;
};
The key difference is a single regex that returns all the matching groups at once.
Here's a regex101 with some examples of it matching/grouping.
It's about double the speed of the #RobG's awesome accepted answer and 4-6x faster than moment.js and date-fns packages. 👍
const createDate = (isoDate) => {
isoDate = new Date(isoDate)
return new Date(Date.UTC(
isoDate.getUTCFullYear(),
isoDate.getUTCMonth(),
isoDate.getUTCDate(),
isoDate.getUTCMinutes(),
isoDate.getUTCSeconds(),
isoDate.getUTCMilliseconds()
));
}
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theRepositionedDate = createDate(iso8601Date);
console.log(theRepositionedDate instanceof Date); // true
console.log(theRepositionedDate);
But, sometimes we want to "ignore" the timezone offset and analyze the data as if it happened in the current timezone.
Ok, then ignore it.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theDate = new Date(iso8601Date.substring(0, 19));
This works because you're creating a Date object from 2020-01-01T00:00:00 - an ISO 8601 date-time without offset.
ECMAScript section 20.3.1.15 - Date Time String Format says:
When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

how to convert "05:30" String value into integer using javascript

I tried to convert the string into integer using parseInt and parseFloat. But my string value is "+05:30" while using parseInt or parseFloat it converts it into 5, but I need exact conversion to 5.30. How could I do this?
My sample code is:
User.findAll({attributes: ['UTC offset'],
where: {
Timezone: { $like: '%'+address }
}
}).then(TimeZoneData => {
if(TimeZoneData.length != 0) {
var offset = parseFloat(TimeZoneData[0].dataValues['UTC DST offset']), // it return 5 only
}
Let's say the time zone offsets are valid, they are in hours and minutes always separated by a colon (':') and preceded by a '+' or '-'.
So
var utcOffset = "+05:30";
var a = uctOffset.split(':');
var hour = +a[0];
var minute = +a[1];
What you do with the hour and minute values is up to you - but if the hour is negative, the minutes might need to be made negative too. I suggest you use isNaN to check the minute is valid if it may be absent:
if( isNaN( minute)
minute = 0;

How to convert/format a date from vb.net to JavaScript? [duplicate]

I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:
/Date(1224043200000)/
From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.
FYI: Here's the solution I came up with using a combination of the answers here:
function getMismatch(id) {
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function (result) {
$("#AuthMerchId").text(result.AuthorizationMerchantId);
$("#SttlMerchId").text(result.SettlementMerchantId);
$("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
$("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
$("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
$("#LastUpdatedBy").text(result.LastUpdateNt);
$("#ProcessIn").text(result.ProcessIn);
}
);
return false;
}
function formatJSONDate(jsonDate) {
var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
return newDate;
}
This solution got my object from the callback method and displayed the dates on the page properly using the date format library.
eval() is not necessary. This will work fine:
var date = new Date(parseInt(jsonDate.substr(6)));
The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor.
I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.
Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.
For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:
var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
You can use this to get a date from JSON:
var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.
For those using Newtonsoft Json.NET, read up on how to do it via Native JSON in IE8, Firefox 3.5 plus Json.NET.
Also the documentation on changing the format of dates written by Json.NET is useful:
Serializing Dates with Json.NET
For those that are too lazy, here are the quick steps. As JSON has a loose DateTime implementation, you need to use the IsoDateTimeConverter(). Note that since Json.NET 4.5 the default date format is ISO so the code below isn't needed.
string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
The JSON will come through as
"fieldName": "2009-04-12T20:44:55"
Finally, some JavaScript to convert the ISO date to a JavaScript date:
function isoDateReviver(value) {
if (typeof value === 'string') {
var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
if (a) {
var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
return new Date(utcMilliseconds);
}
}
return value;
}
I used it like this
$("<span />").text(isoDateReviver(item.fieldName).toLocaleString()).appendTo("#" + divName);
The original example:
/Date(1224043200000)/
does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)
I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.
In a WCF service I have:
[OperationContract]
[WebInvoke(
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest
)]
ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );
ApptVisitLinkInfo is defined simply:
public class ApptVisitLinkInfo {
string Field1 { get; set; }
DateTime Field2 { get; set; }
...
}
When "Field2" is returned as Json from the service the value is:
/Date(1224043200000-0600)/
Notice the timezone offset included as part of the value.
The modified regex:
/\/Date\((.*?)\)\//gi
It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.
The resulting line of JavaScript for the replace is:
replace(/\/Date\((.*?)\)\//gi, "new Date($1)");
Don't repeat yourself - automate date conversion using $.parseJSON()
Answers to your post provide manual date conversion to JavaScript dates. I've extended jQuery's $.parseJSON() just a little bit, so it's able to automatically parse dates when you instruct it to. It processes ASP.NET formatted dates (/Date(12348721342)/) as well as ISO formatted dates (2010-01-01T12.34.56.789Z) that are supported by native JSON functions in browsers (and libraries like json2.js).
Anyway. If you don't want to repeat your date conversion code over and over again I suggest you read this blog post and get the code that will make your life a little easier.
Click here to check the Demo
JavaScript/jQuery
var = MyDate_String_Value = "/Date(1224043200000)/"
var value = new Date
(
parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
);
var dat = value.getMonth() +
1 +
"/" +
value.getDate() +
"/" +
value.getFullYear();
Result - "10/15/2008"
If you say in JavaScript,
var thedate = new Date(1224043200000);
alert(thedate);
you will see that it's the correct date, and you can use that anywhere in JavaScript code with any framework.
Updated
We have an internal UI library that has to cope with both Microsoft's ASP.NET built-in JSON format, like /Date(msecs)/, asked about here originally, and most JSON's date format including JSON.NET's, like 2014-06-22T00:00:00.0. In addition we need to cope with oldIE's inability to cope with anything but 3 decimal places.
We first detect what kind of date we're consuming, parse it into a normal JavaScript Date object, then format that out.
1) Detect Microsoft Date format
// Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'
function looksLikeMSDate(s) {
return /^\/Date\(/.test(s);
}
2) Detect ISO date format
var isoDateRegex = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d\d?\d?)?([\+-]\d\d:\d\d|Z)?$/;
function looksLikeIsoDate(s) {
return isoDateRegex.test(s);
}
3) Parse MS date format:
function parseMSDate(s) {
// Jump forward past the /Date(, parseInt handles the rest
return new Date(parseInt(s.substr(6)));
}
4) Parse ISO date format.
We do at least have a way to be sure that we're dealing with standard ISO dates or ISO dates modified to always have three millisecond places (see above), so the code is different depending on the environment.
4a) Parse standard ISO Date format, cope with oldIE's issues:
function parseIsoDate(s) {
var m = isoDateRegex.exec(s);
// Is this UTC, offset, or undefined? Treat undefined as UTC.
if (m.length == 7 || // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC
(m.length > 7 && (
!m[7] || // Array came back length 9 with undefined for 7 and 8
m[7].charAt(0) != '.' || // ms portion, no tz offset, or no ms portion, Z
!m[8] || // ms portion, no tz offset
m[8] == 'Z'))) { // ms portion and Z
// JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.
var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));
} else {
// local
var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);
}
return d;
}
4b) Parse ISO format with a fixed three millisecond decimal places - much easier:
function parseIsoDate(s) {
return new Date(s);
}
5) Format it:
function hasTime(d) {
return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());
}
function zeroFill(n) {
if ((n + '').length == 1)
return '0' + n;
return n;
}
function formatDate(d) {
if (hasTime(d)) {
var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());
} else {
var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
}
return s;
}
6) Tie it all together:
function parseDate(s) {
var d;
if (looksLikeMSDate(s))
d = parseMSDate(s);
else if (looksLikeIsoDate(s))
d = parseIsoDate(s);
else
return null;
return formatDate(d);
}
The below old answer is useful for tying this date formatting into jQuery's own JSON parsing so you get Date objects instead of strings, or if you're still stuck in jQuery <1.5 somehow.
Old Answer
If you're using jQuery 1.4's Ajax function with ASP.NET MVC, you can turn all DateTime properties into Date objects with:
// Once
jQuery.parseJSON = function(d) {return eval('(' + d + ')');};
$.ajax({
...
dataFilter: function(d) {
return d.replace(/"\\\/(Date\(-?\d+\))\\\/"/g, 'new $1');
},
...
});
In jQuery 1.5 you can avoid overriding the parseJSON method globally by using the converters option in the Ajax call.
http://api.jquery.com/jQuery.ajax/
Unfortunately you have to switch to the older eval route in order to get Dates to parse globally in-place - otherwise you need to convert them on a more case-by-case basis post-parse.
There is no built in date type in JSON. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.
I also had to search for a solution to this problem and eventually I came across moment.js which is a nice library that can parse this date format and many more.
var d = moment(yourdatestring)
It saved some headache for me so I thought I'd share it with you. :)
You can find some more info about it here: http://momentjs.com/
I ended up adding the "characters into Panos's regular expression to get rid of the ones generated by the Microsoft serializer for when writing objects into an inline script:
So if you have a property in your C# code-behind that's something like
protected string JsonObject { get { return jsSerialiser.Serialize(_myObject); }}
And in your aspx you have
<script type="text/javascript">
var myObject = '<%= JsonObject %>';
</script>
You'd get something like
var myObject = '{"StartDate":"\/Date(1255131630400)\/"}';
Notice the double quotes.
To get this into a form that eval will correctly deserialize, I used:
myObject = myObject.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
I use Prototype and to use it I added
String.prototype.evalJSONWithDates = function() {
var jsonWithDates = this.replace(/"\/Date\((\d+)\)\/"/g, 'new Date($1)');
return jsonWithDates.evalJSON(true);
}
In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:
(function () {
var DATE_START = "/Date(";
var DATE_START_LENGTH = DATE_START.length;
function isDateString(x) {
return typeof x === "string" && x.startsWith(DATE_START);
}
function deserializeDateString(dateString) {
var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
return utcDate;
}
function convertJSONDates(key, value) {
if (isDateString(value)) {
return deserializeDateString(value);
}
return value;
}
window.jQuery.ajaxSetup({
converters: {
"text json": function(data) {
return window.JSON.parse(data, convertJSONDates);
}
}
});
}());
I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.
This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.
Using the jQuery UI datepicker - really only makes sense if you're already including jQuery UI:
$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6))));
output:
October 15, 2008
Don't over-think this. Like we've done for decades, pass a numeric offset from the de-facto standard epoch of 1 Jan 1970 midnight GMT/UTC/&c in number of seconds (or milliseconds) since this epoch. JavaScript likes it, Java likes it, C likes it, and the Internet likes it.
Everyone of these answers has one thing in common: they all store dates as a single value (usually a string).
Another option is to take advantage of the inherent structure of JSON, and represent a date as list of numbers:
{ "name":"Nick",
"birthdate":[1968,6,9] }
Of course, you would have to make sure both ends of the conversation agree on the format (year, month, day), and which fields are meant to be dates,... but it has the advantage of completely avoiding the issue of date-to-string conversion. It's all numbers -- no strings at all. Also, using the order: year, month, day also allows proper sorting by date.
Just thinking outside the box here -- a JSON date doesn't have to be stored as a string.
Another bonus to doing it this way is that you can easily (and efficiently) select all records for a given year or month by leveraging the way CouchDB handles queries on array values.
Posting in awesome thread:
var d = new Date(parseInt('/Date(1224043200000)/'.slice(6, -2)));
alert('' + (1 + d.getMonth()) + '/' + d.getDate() + '/' + d.getFullYear().toString().slice(-2));
Just to add another approach here, the "ticks approach" that WCF takes is prone to problems with timezones if you're not extremely careful such as described here and in other places. So I'm now using the ISO 8601 format that both .NET & JavaScript duly support that includes timezone offsets. Below are the details:
In WCF/.NET:
Where CreationDate is a System.DateTime; ToString("o") is using .NET's Round-trip format specifier that generates an ISO 8601-compliant date string
new MyInfo {
CreationDate = r.CreationDate.ToString("o"),
};
In JavaScript
Just after retrieving the JSON I go fixup the dates to be JavaSript Date objects using the Date constructor which accepts an ISO 8601 date string...
$.getJSON(
"MyRestService.svc/myinfo",
function (data) {
$.each(data.myinfos, function (r) {
this.CreatedOn = new Date(this.CreationDate);
});
// Now each myinfo object in the myinfos collection has a CreatedOn field that is a real JavaScript date (with timezone intact).
alert(data.myinfos[0].CreationDate.toLocaleString());
}
)
Once you have a JavaScript date you can use all the convenient and reliable Date methods like toDateString, toLocaleString, etc.
var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
Is there another option without using the jQuery library?
This may can also help you.
function ToJavaScriptDate(value) { //To Parse Date from the Returned Parsed Date
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
I get the date like this:
"/Date(1276290000000+0300)/"
In some examples the date is in slightly different formats:
"/Date(12762900000000300)/"
"Date(1276290000000-0300)"
etc.
So I came up with the following RegExp:
/\/+Date\(([\d+]+)\)\/+/
and the final code is:
var myDate = new Date(parseInt(jsonWcfDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));
Hope it helps.
Update:
I found this link from Microsoft:
How do I Serialize Dates with JSON?
This seems like the one we are all looking for.
Below is a pretty simple solution for parsing JSON dates. Use the below functions as per your requirement. You just need to pass the JSON format Date fetched as a parameter to the functions below:
function JSONDate(dateStr) {
var m, day;
jsonDate = dateStr;
var d = new Date(parseInt(jsonDate.substr(6)));
m = d.getMonth() + 1;
if (m < 10)
m = '0' + m
if (d.getDate() < 10)
day = '0' + d.getDate()
else
day = d.getDate();
return (m + '/' + day + '/' + d.getFullYear())
}
function JSONDateWithTime(dateStr) {
jsonDate = dateStr;
var d = new Date(parseInt(jsonDate.substr(6)));
var m, day;
m = d.getMonth() + 1;
if (m < 10)
m = '0' + m
if (d.getDate() < 10)
day = '0' + d.getDate()
else
day = d.getDate();
var formattedDate = m + "/" + day + "/" + d.getFullYear();
var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var formattedTime = hours + ":" + minutes + ":" + d.getSeconds();
formattedDate = formattedDate + " " + formattedTime;
return formattedDate;
}
You also can use the JavaScript library moment.js, which comes in handy when you plan do deal with different localized formats and perform other operations with dates values:
function getMismatch(id) {
$.getJSON("Main.aspx?Callback=GetMismatch",
{ MismatchId: id },
function (result) {
$("#AuthMerchId").text(result.AuthorizationMerchantId);
$("#SttlMerchId").text(result.SettlementMerchantId);
$("#CreateDate").text(moment(result.AppendDts).format("L"));
$("#ExpireDate").text(moment(result.ExpiresDts).format("L"));
$("#LastUpdate").text(moment(result.LastUpdateDts).format("L"));
$("#LastUpdatedBy").text(result.LastUpdateNt);
$("#ProcessIn").text(result.ProcessIn);
}
);
return false;
}
Setting up localization is as easy as adding configuration files (you get them at momentjs.com) to your project and configuring the language:
moment.lang('de');
Check up the date ISO standard; kind of like this:
yyyy.MM.ddThh:mm
It becomes 2008.11.20T22:18.
This is frustrating. My solution was to parse out the "/ and /" from the value generated by ASP.NET's JavaScriptSerializer so that, though JSON may not have a date literal, it still gets interpreted by the browser as a date, which is what all I really want:{"myDate":Date(123456789)}
Custom JavaScriptConverter for DateTime?
I must emphasize the accuracy of Roy Tinker's comment. This is not legal JSON. It's a dirty, dirty hack on the server to remove the issue before it becomes a problem for JavaScript. It will choke a JSON parser. I used it for getting off the ground, but I do not use this any more. However, I still feel the best answer lies with changing how the server formats the date, for example, ISO as mentioned elsewhere.
A late post, but for those who searched this post.
Imagine this:
[Authorize(Roles = "Administrator")]
[Authorize(Roles = "Director")]
[Authorize(Roles = "Human Resources")]
[HttpGet]
public ActionResult GetUserData(string UserIdGuidKey)
{
if (UserIdGuidKey!= null)
{
var guidUserId = new Guid(UserIdGuidKey);
var memuser = Membership.GetUser(guidUserId);
var profileuser = Profile.GetUserProfile(memuser.UserName);
var list = new {
UserName = memuser.UserName,
Email = memuser.Email ,
IsApproved = memuser.IsApproved.ToString() ,
IsLockedOut = memuser.IsLockedOut.ToString() ,
LastLockoutDate = memuser.LastLockoutDate.ToString() ,
CreationDate = memuser.CreationDate.ToString() ,
LastLoginDate = memuser.LastLoginDate.ToString() ,
LastActivityDate = memuser.LastActivityDate.ToString() ,
LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
IsOnline = memuser.IsOnline.ToString() ,
FirstName = profileuser.FirstName ,
LastName = profileuser.LastName ,
NickName = profileuser.NickName ,
BirthDate = profileuser.BirthDate.ToString() ,
};
return Json(list, JsonRequestBehavior.AllowGet);
}
return Redirect("Index");
}
As you can see, I'm utilizing C# 3.0's feature for creating the "Auto" Generics. It's a bit lazy, but I like it and it works.
Just a note: Profile is a custom class I've created for my web application project.
FYI, for anyone using Python on the server side: datetime.datetime().ctime() returns a string that is natively parsable by "new Date()". That is, if you create a new datetime.datetime instance (such as with datetime.datetime.now), the string can be included in the JSON string, and then that string can be passed as the first argument to the Date constructor. I haven't yet found any exceptions, but I haven't tested it too rigorously, either.
Mootools solution:
new Date(Date(result.AppendDts)).format('%x')
Requires mootools-more. Tested using mootools-1.2.3.1-more on Firefox 3.6.3 and IE 7.0.5730.13
var obj = eval('(' + "{Date: \/Date(1278903921551)\/}".replace(/\/Date\((\d+)\)\//gi, "new Date($1)") + ')');
var dateValue = obj["Date"];
Add the jQuery UI plugin in your page:
function DateFormate(dateConvert) {
return $.datepicker.formatDate("dd/MM/yyyy", eval('new ' + dateConvert.slice(1, -1)));
};
What if .NET returns...
return DateTime.Now.ToString("u"); //"2013-09-17 15:18:53Z"
And then in JavaScript...
var x = new Date("2013-09-17 15:18:53Z");

Comparing 2 strings with number values JS

Im trying to check to see if current time is lower than time that is responded from an API. Problem is they are both strings. The API response contains characters such as : and -, so parseInt is not working (at least that's my theory why its not working)
var d = new Date();
var hour = d.getHours();
var minutes = d.getMinutes();
var year = d.getFullYear();
var month = d.getMonth() +1;
var day = d.getDate();
var seconds = d.getSeconds();
var time = year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds;
time returns
"2016-11-7 15:48:2"
API Response is
"2016-11-07 20:06:00"
I have confirmed they are both strings
time < APIresponse
Always returns false
Are there any known solutions? Thanks in advance.
Preface: Timezone
Your current code assumes that the date/time you're getting from the API is in "local time," because you're comparing it with the current date/time in the browser's local timezone. APIs frequently provide date/times in UTC rather than "local" time, so beware of that assumption and double-check it.
If you want to do it at the string level
...you need to ensure when building time that you zero-pad the numbers, so for instance not just 7 for the day of the month, but 07. Then you'll end up with strings that have the fields in a valid comparable order (because the most significant field [year] is first, and the least significant field [seconds] is last), so a lexicographic comparison of the strings is valid.
So for instance, you'd create time like this:
var time = pad(year, 4) + '-' + pad(month, 2) + '-' + pad(day, 2) + ' ' + pad(hour, 2) + ':' + pad(minutes, 2) + ':' + pad(seconds, 2);
...where pad is a function you define that adds as many 0s as needed to ensure the string is as long as the second argument defines.
Then you can do:
if (time < timeStringFromAPI)
Note: If the API's response is giving you the date/time in UTC rather than local time, you'll need to use the UTC version of the accessor functions (e.g., getUTCHours, getUTCFullYear, etc.) rather than the ones you're using, which are for local time.
If you want to do it at the date level
...then you need to convert the date you're getting from the API to a Date. It's almost in a form you can reliable parse on modern browsers,
but not quite; some browsers will parse that string as local time, others as UTC.
If you're sure it's in local time, then the best thing to do is split it into its parts and use the multipart Date constructor:
var parts = timeStringFromAPI.split(/[-:]/);
var apiDate = new Date(
+parts[0], // Year
+parts[1] - 1, // Month
+parts[2], // Day
+parts[3], // Hours
+parts[4], // Minutes
+parts[5] // Seconds
);
If you're sure it's in UTC, then you can either do the above but with new Date(Date.UTC(...)) rather than just new Date(...), or you can put the string into the JavaScript date/time format and parse that:
var apiDate = new Date(timeStringFromAPI.replace(" ", "T") + "Z");
That takes the "2016-11-07 20:06:00" and changes it to "2016-11-07T20:06:00Z", which can reliably be parsed on all non-obsolete browsers.
Then you can do
if (new Date() < apiDate) {
try this :
var curDate = new Date();
then compare in this way
if (new Date(yourdate) <= curDate)
{
something...
}
var d1 = "2016-11-7 15:48:2";
var d2 = "2016-11-07 20:06:00";
if (new Date(d1) < new Date(d2)) {
alert('true')
}

Categories

Resources