First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601
So I have 2 kinds of date coming from json.
m = '201811';
n = '/Date(1433030400000)/';
I am trying to use moment.js to format time, but I can not find appropriate methods for it I guess.
moment(m).format('YYYY DD') //"201811 01"
and the n value I can not understand it leads to this output :
moment(m).format('YYYY DD')//"2015 31"
When you pass a date to moment() constructor, you might have to specify in what format it is.
So for the first date you would need to do:
moment(m, 'YYYYMM').format('YYYY MM'); // if the date is indeed in the form YYYYMM
For the second date, just extract the numeric part from the string and feed it to moment:
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
See the snippet:
var m = '201811';
var n = '/Date(1433030400000)/';
alert(moment(m, 'YYYYMM').format('YYYY MM'));
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
alert(moment(+ts[1]).format('YYYY MM'));
<script src="http://momentjs.com/downloads/moment.js"></script>
EDIT:
thanks to #MattJohnson, if you have at least moment version 1.3.0, you can simply pass the string in the form /Date(1433030400000)/ to the moment() constructor, and it will automatically detect the proper format, see also here.
Just pass them to moment in the following format:
var m = '201811';
var n = '/Date(1433030400000)/';
var formattedM = window.moment(m, 'YYYYMM').format('YYYY MMM DD'); //2018 Nov 01
var formattedN = window.moment(n).format('YYYY MMM DD'); //2015 May 31
I've dropped an example into jsbin.
Thanks to Matt Johnson for pointing out that moment can take the /Date(1433030400000)/ format.
I have been using CDate in my program and the worry part is , it works only in IE.
cdate(strValue) . If I pass the value of strvalue as 01/02 , it returns as Wed Jan 2 etc . Am looking for the same implementation in javascript so that it will work in other browsers. Am trying my best to find one, but am not lucky. Can anyone tell me what api we can use in javascript instead of using CDate ??
You can try the following code:
var comp = "05/04".split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var date = new Date(null, m - 1, d);
date.toDateString(); //this line will return the date
Now you can parse the string and manipulate string according to your need.
i am getting string from server and i need to covert that fetching string in to new date object.. for doing this, i tried this function, but no use, any one can help me to convert strings to date object?
my code is :
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.71417&lan=74.00639',
getLondonLocalTime : 'getTime.php?lat=51.5&lan=0.1166667',
getChennaiLocalTime : 'getTime.php?lat=13.0833333&lan=80.2833333',
getBangaloreLocalTime:'getTime.php?lat=12.9833333&lan=77.5833333'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
var newdate = $(response).find('localtime').text();
if(key == "getNewYorkLocalTime"){
var newyourktime = new Date(newdate);
newyourktime.getTime()
}
});
});
but, the newyourktime is showing local time only.. any help please? as well i am getting the response from server is : 17 Nov 2011 18:09:47 - like this.
Use http://www.datejs.com/
As an example:
var newyourktime = Date.parse('2011-11-11, 11:11 AM');
alert(newyourktime.toString('dd/mm/yyyy HH:mm:ss EST'));
Check out the Datejs library documentation to meet your requirements, after your date string is parsed, you can do a lot with it.
This will try to parse the date using the client machine own local settings, which is not good.
Instead of passing it as string, pass it as the total seconds that passed since 1/1/1970 at midnight and use this number when constructing the new Date object of JavaScript.
For example pass this number: 1321614000000 and you will get November 18th 2011, 1 PM
You could use substr
day = newdate.substr(0,2);
month = newdate.substr(3,3);
year = newdate.substr(7,4);
var newyorktime = new Date(year, month, day);
Substr
My date objects in JavaScript are always represented by UTC +2 because of where I am located. Hence like this
Mon Sep 28 10:00:00 UTC+0200 2009
Problem is doing a JSON.stringify converts the above date to
2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)
What I need is for the date and time to be honoured but it's not, hence it should be
2009-09-28T10:00:00Z (this is how it should be)
Basically I use this:
var jsonData = JSON.stringify(jsonObject);
I tried passing a replacer parameter (second parameter on stringify) but the problem is that the value has already been processed.
I also tried using toString() and toUTCString() on the date object, but these don't give me what I want either..
Can anyone help me?
Recently I have run into the same issue. And it was resolved using the following code:
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
JSON uses the Date.prototype.toISOString function which does not represent local time -- it represents time in unmodified UTC -- if you look at your date output you can see you're at UTC+2 hours, which is why the JSON string changes by two hours, but if this allows the same time to be represented correctly across multiple time zones.
date.toJSON() prints the UTC-Date into a String formatted (So adds the offset with it when converts it to JSON format).
date = new Date();
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
Just for the record, remember that the last "Z" in "2009-09-28T08:00:00Z" means that the time is indeed in UTC.
See http://en.wikipedia.org/wiki/ISO_8601 for details.
Out-of-the-box solution to force JSON.stringify ignore timezones:
Pure javascript (based on Anatoliy answer):
// Before: JSON.stringify apply timezone offset
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
// After: JSON.stringify keeps date as-is!
Date.prototype.toJSON = function(){
const hoursDiff = this.getHours() - this.getTimezoneOffset() / 60;
this.setHours(hoursDiff);
return this.toISOString();
};
string = JSON.stringify(date);
console.log(string);
Using moment + moment-timezone libraries:
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
Date.prototype.toJSON = function(){
return moment(this).format("YYYY-MM-DDTHH:mm:ss:ms");;
};
string = JSON.stringify(date);
console.log(string);
<html>
<header>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
</header>
</html>
Here is another answer (and personally I think it's more appropriate)
var currentDate = new Date();
currentDate = JSON.stringify(currentDate);
// Now currentDate is in a different format... oh gosh what do we do...
currentDate = new Date(JSON.parse(currentDate));
// Now currentDate is back to its original form :)
you can use moment.js to format with local time:
Date.prototype.toISOString = function () {
return moment(this).format("YYYY-MM-DDTHH:mm:ss");
};
I'm a little late but you can always overwrite the toJson function in case of a Date using Prototype like so:
Date.prototype.toJSON = function(){
return Util.getDateTimeString(this);
};
In my case, Util.getDateTimeString(this) return a string like this: "2017-01-19T00:00:00Z"
I run into this a bit working with legacy stuff where they only work on east coast US and don't store dates in UTC, it's all EST. I have to filter on the dates based on user input in the browser so must pass the date in local time in JSON format.
Just to elaborate on this solution already posted - this is what I use:
// Could be picked by user in date picker - local JS date
date = new Date();
// Create new Date from milliseconds of user input date (date.getTime() returns milliseconds)
// Subtract milliseconds that will be offset by toJSON before calling it
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
So my understanding is this will go ahead and subtract time (in milliseconds (hence 60000) from the starting date based on the timezone offset (returns minutes) - in anticipation for the addition of time toJSON() is going to add.
JavaScript normally convert local timezone to UTC .
date = new Date();
date.setMinutes(date.getMinutes()-date.getTimezoneOffset())
JSON.stringify(date)
Usually you want dates to be presented to each user in his own local time-
that is why we use GMT (UTC).
Use Date.parse(jsondatestring) to get the local time string,
unless you want your local time shown to each visitor.
In that case, use Anatoly's method.
Got around this issue by using the moment.js library (the non-timezone version).
var newMinDate = moment(datePicker.selectedDates[0]);
var newMaxDate = moment(datePicker.selectedDates[1]);
// Define the data to ask the server for
var dataToGet = {"ArduinoDeviceIdentifier":"Temperatures",
"StartDate":newMinDate.format('YYYY-MM-DD HH:mm'),
"EndDate":newMaxDate.format('YYYY-MM-DD HH:mm')
};
alert(JSON.stringify(dataToGet));
I was using the flatpickr.min.js library. The time of the resulting JSON object created matches the local time provided but the date picker.
Here is something really neat and simple (atleast I believe so :)) and requires no manipulation of date to be cloned or overloading any of browser's native functions like toJSON (reference: How to JSON stringify a javascript Date and preserve timezone, courtsy Shawson)
Pass a replacer function to JSON.stringify that stringifies stuff to your heart's content!!! This way you don't have to do hour and minute diffs or any other manipulations.
I have put in console.logs to see intermediate results so it is clear what is going on and how recursion is working. That reveals something worthy of notice: value param to replacer is already converted to ISO date format :). Use this[key] to work with original data.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
I ran into the same problem.
The way I resolvet it was:
var currentTime = new Date();
Console.log(currentTime); //Return: Wed Sep 15 13:52:09 GMT-05:00 2021
Console.log(JSON.stringify(currentTime)); //Return: "2021-09-15T18:52:09.891Z"
var currentTimeFixed = new Date(currentTime.setHours(currentTime.getHours() - (currentTime.getUTCHours() - currentTime.getHours())));
Console.log(JSON.stringify(currentTimeFixed)); //Return: "2021-09-15T13:52:09.891Z"
I wrote the following code blog where it makes service calls.. it will try to serializable the json in every post submission, it will format to local date it again.
protected async post(endPoint: string, data, panelName?: string, hasSuccessMessage: boolean = false): Promise<Observable<any>> {
const options = this.InitHeader(true);
const url: string = this._baseUrl + endPoint;
Date.prototype.toJSON = function () {
return moment(this).format("YYYY-MM-DDThh:mm:00.000Z");;
};
return await this._http.post(url, data, options).pipe(map(response => {
return this.Map<any>(response, null);
}));
}
All boils down to if your server backend is timezone-agnostic or not.
If it is not, then you need to assume that timezone of server is the same as client, or transfer information about client's timezone and include that also into calculations.
a PostgreSQL backend based example:
select '2009-09-28T08:00:00Z'::timestamp -> '2009-09-28 08:00:00' (wrong for 10am)
select '2009-09-28T08:00:00Z'::timestamptz -> '2009-09-28 10:00:00+02'
select '2009-09-28T08:00:00Z'::timestamptz::timestamp -> '2009-09-28 10:00:00'
The last one is probably what you want to use in database, if you are not willing properly implement timezone logic.
Instead of toJSON, you can use format function which always gives the correct date and time + GMT
This is the most robust display option. It takes a string of tokens
and replaces them with their corresponding values.
I tried this in angular 8 :
create Model :
export class Model { YourDate: string | Date; }
in your component
model : Model;
model.YourDate = new Date();
send Date to your API for saving
When loading your data from API you will make this :
model.YourDate = new Date(model.YourDate+"Z");
you will get your date correctly with your time zone.
In this case I think you need transform the date to UNIX timestamp
timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);
After that you can re use it to create a date object and format it. Example with javascript and toLocaleDateString ( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )
newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
"fr-FR",
]);
If you use stringify to use AJAX, now it's not useful. You just need to send timestamp and get it in your script:
$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));
Be aware that getTime() will return a time in milliseconds and the PHP function setTimestamp take time in seconds. It's why you need to divide by 1000 and round.
In Angular place the following in index.js script section:
setTimeout(function (){
Date.prototype.toJSON = function(){
return new Date(this).toLocaleDateString("en-US") + " "+new Date(this).toLocaleTimeString();
}},1000);