We are using the following js lib from Microsoft
https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js
var datetimehigh = new Date(2011,01,12,14,45,55,596);
var sDate = datetimehigh.format("dd/MM/yyyy HH:mm:ss sss");
I cannot get the millisecond part to work.Note that format comes from Microsoft's Mvc Ajax lib.
If you are using the native Date javascript object, you can simply use .toISOString method to get a formatted string with milliseconds:
const date = new Date();
const dateString = date.toISOString(); // "2020-01-06T19:57:12.146Z"
Note that using .toString won't give you milliseconds precision.
It's indicated by an f:
"dd/MM/yyyy HH:mm:ss fff"
Use 'S' for milliseconds formatting:
"dd/MM/yyyy HH:mm:ss:SSS"
Using the date format library, it should be something like this:
var nowMilliseconds = new Date().format("yyyy-mm-dd HH:MM:ss l");
http://blog.stevenlevithan.com/archives/date-time-format
L for milliseconds with two digits
l (minus) for milliseconds with three digits
Here's how I do it:
function date_to_string_with_milliseconds(date){
let date_str = date.toString()
let date_without_milliseconds = new Date(date_str) // truncated date since milliseconds are not included
let milliseconds_delta = date - date_without_milliseconds
let date_str_with_milliseconds = date_str.replace(/(^.*:\d\d:\d\d)(.*$)/, `$1:${milliseconds_delta}$2`)
return date_str_with_milliseconds
}
Usage:
date_to_string_with_milliseconds(new Date(Date.now())).toString()
// outputs 'Wed Nov 30 2022 16:40:42:991 GMT+0530 (India Standard Time)'
Doing it this way has a couple of advantages:
The date string that you get as output can be converted back to a
Date object.
This doesn't change the original date object in any
way since you only need a string representation.
Related
let's say I have this date as input :
var _dateA = 2018-11-15T11:13:26.687Z
If I'm doing, whatever,
var _dateB = new Date(_date)
or
var _dateB = moment(_date)
I get this as result ==>
_dateB = Thu Nov 15 2018 12:13:26 GMT+0100 (heure normale d’Europe centrale)
I understood that there's timezone trouble, but how can I get a Date object or Moment object, without having this one hour more?
Wanted result => Thu Nov 15 2018 11:13:26 GMT+0100
Current result => Thu Nov 15 2018 12:13:26 GMT+0100
You need to use Date.toUTCString() that converts date to string, using the UTC time zone
var _dateA = '2018-11-15T11:13:26.687Z';
var _dateB = new Date(_dateA);
console.log(_dateB.toUTCString());
When you "output" a Date object via console.log(), alert(), etc the toString() method is used by default, converting the date object to a local timezone string for display (which is why you are seeing your date in your local time).
Parsing date strings with the Date constructor is not recommended (although, I suspect that most browsers probably handle ISO 8601 dates, like the one in your question, fairly well) - see the dateString parameter note here. So, if you need to construct a date object as well as output a date string, then you could parse the ISO 8601 string with split() using a regex character set for multiple delimiters, then construct a UTC date object with new Date(Date.UTC(...)). You could also do this with moment.js but the below should illustrate what is happening in a bit more detail.
For example:
const text = '2018-11-15T11:13:26.687Z'
const [y, m, d, hh, mm, ss, ms] = text.split(/[-T:.Z]/);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(date.toLocaleString()); // date string in local timezone
console.log(date.toUTCString()); // UTC date string
console.log(JSON.stringify(date)); // ISO 8601 date string in most browsers
Here's my Scenario:
I have a value for DateTime in this Format only:
'2017-05-01T07:40:00.000+10:00'
but need this to convert to a Readable Date Time Format like this:
eg. 05/01/2017 07:40 AM
- Without Converting it to your Local Time, because if i use
var t = "2017-05-01T07:40:00.000+10:00";
var d = new Date(t); //using javascript Date object
var z = moment(t); // or using moment.js:
var d and z both have the same output like this:
Mon May 01 2017 05:40:00 GMT+0800 (Taipei Standard Time)
//05/01/2017 05:40 AM
it's minus 2 Hour in my Local Timezone GMT +8, but i don't want it to be converted that way.
i just need the exact Time which is 05/01/2017 07:40 AM
Is there other way to get my desired output in javascript?
Try use with Regex pattern /-|:|T/g for split()
var t = "2017-05-01T07:40:00.000+10:00";
var s =t.split(/-|:|T/g).slice(0,5)
var c =parseInt(s[3]) > 12 ? parseInt(s[3])-12 : s[3];
var f =parseInt(s[3]) > 12 ? 'PM' : 'AM';
console.log(s[1]+'/'+s[2]+'/'+s[0]+' '+c+':'+s[4]+' '+f);
You may refer to this post
Stop javascript Date function from changing timezone offset
It also mentioned a sample on how to use 'moment' to pinpoint the datetime to the timezone you want to show (GMT+10).
I think so this will help you.
var t = "2017-05-01T07:40:00.000Z";
var d = new Date(t); //using javascript Date object
I m having a date time text which i m converting to local dateTime using the javascript date time function toString();
var txt = $(e).html();
var date = new Date(txt);
$(e).html (date.toString('yyyy-mm-dd'));
Now the toString method of javascript does not accept any parameters.
It always comes up with this format -
Tue Aug 26 2014 03:30:34 GMT+0530 (India Standard Time)
I could not change the date format and had to go with a library date.js as here
Any help without any js frameworks.
Regards
You can parse it yourself, something like:
var date = new Date(txt);
var dateStr = date.getDate()+'/'+date.getMonth()+'/'+date.getYear();
1) You can use toLocaleFormat() - MDN. But seems that it supports only in Firefox.
2) Write your own function which will do it. I provide example so you got main idea for it:
function dateFormat(format, date) {
date = date || new Date();
return format.replace('%m', date.getMonth());
}
var date = new Date();
console.log(dateFormat('Current month - %m', date));
3) Use libraries.
I have the following input and i can change the source of this data
Input
var strDate = "/Date(1391402871117+0100)/";
I can convert it to a date using eval, but i really dont want to eval
var DateResult1 = eval ("new Date(1391402871117+0100)");
console.log(DateResult1); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
I did try this, sadly do not work:
// Remove /Date( )/
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult3 = new Date(strDate);
console.log(DateResult3); //Date {Invalid Date}
When i write result of strDate i manual with out " it work.
var DateResult2 = new Date(1391402871117+0100);
console.log(DateResult2); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
How can convert the input data into a date with out using eval or any library?
You are very likely not getting a correct result out of this code:
var DateResult2 = new Date(1391402871117+0100);
The problem is the addition: 1391402871117+0100. 0100 is an octal constant, equal to 64 in decimal, which would add 64 milliseconds to the 1391402871117 timestamp. It seems likely to be indended as a time zone instead, but the Date constructor does not support time zones — only UTC and the local time zone of the browser.
Since UNIX timestamps are actually absolute (they are always in UTC), using just the timestamp would result in a Date instance referencing the correct instant in time, but possibly at another time zone. You can disregard the +0100 part, by converting the "1391402871117+0100" into an integer using parseInt:
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult2 = new Date(parseInt(strDate));
If you can change the data source, as you say, why not do this?
Have your data source generate something like this, to add the timezone offset to the timestamp:
// convert timezone offset hours into seconds and add them to the timestamp
return (unixTimestamp + (timezoneOffsetHours * 3600));
Then you can do something like this in your JS:
// Math.floor works faster than parseInt to convert a string to integer :)
var timestamp = Math.floor(result of above timestamp generation);
var DateResult = new Date(timestamp);
The reason:
new Date() can't handle timezones specified in this way (or at all as far as I can Google)
try by parsing string to int:
var strDate = "/Date(1391402871117+0100)/";
strDate = strDate.replace(/[^\d+]/g, '');
var DateResult3 = new Date(parseInt(strDate.split('+')[0]) + parseInt(strDate.split('+')[1]));
console.log(DateResult3);
Here is Demo
The format of my date string looks like this: yyyy-MM-ddTHH:mm:ss-0Z00
Example 1: 2010-03-05T07:03:51-0800
Example 2: 2010-07-01T20:23:00-0700
I need to create a date object using these date strings. new Date() does not work on this string.
Please help me convert these date strings into a date objects with the local timezone.
Thank you!
Edit: I am using this in Pentaho Data Integration 4.3.0.
Take my timezone as an example (AEST):
function parseDate(str_date) {
return new Date(Date.parse(str_date));
}
var str_date = "2015-05-01T22:00:00+10:00"; //AEST time
var locale_date = parseDate(str_date);
locale_date: Fri May 01 2015 22:00:00 GMT+1000 (AEST)
var str_date = "2015-05-01T22:00:00+00:00" //UTC time
var locale_date = parseDate(str_date);
locale_date: Sat May 02 2015 08:00:00 GMT+1000 (AEST)
You can use a library such as Moment.js to do this.
See the String + Format parsing.
http://momentjs.com/docs/#/parsing/string-format/
The following should parse your date you provided, but you may need to modify it for your needs.
var oldDate = "2010-03-05T07:03:51-0800";
var dateObj = moment(oldDate, "YYY-MM-DDTHH:mm:ssZ").toDate();
Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.
http://momentjs.com/docs/#/parsing/string/
Alternative
A second way of doing this is Date.js, another library that seems to parse the format just fine. http://www.datejs.com
Date String:
var strDate = "2010-07-01T20:23:00-0700";
To local time representation in native JS Date object:
var ltzDate = (new Date(strDate)).toLocaleString();