JavaScript new Date().toLocaleString() length - javascript

In I.E. 11, in the console window, if I type new Date().toLocaleString(), I get something like "2/4/2016 9:12:05 AM". However, if I add .length, I get 32. The string is 19 "readable" characters, so what's up with the 32 and is there an option I can invoke that will give me a string of length 19?
If I type new Date(new Date().toLocaleString()), I get [date] Invalid Date, whereas if I type new Date(new Date("2/4/2016 9:12:05 AM")) I get a legitimate date.
My locale is "en-US".

You are taking the lenght of the whole string.
In this case what this function return is :
Thu Feb 04 2016 17:28:09 GMT+0200 (FLE Standard Time) <-- 32 chars.
Try to get the new Date as a variable and use it.
var example = new Date();

This happens with IE11 as well. I have encountered same issue, fixed it by using below date, this way you do not see any invisible empty character.
var cleanDate = (new Date()).toISOString();
Here is solution for specific to your problem, if you do not want to use above method of getting date.
//Custom extension method to replace all found value.
String.prototype.replaceAll = function(find, replace) {
var target = this;
return target.split(find).join(replace);
};
//Find there is invisible empty character
var emptyCode = (new Date()).toLocaleString().charCodeAt(0);
var cleanDate = undefined;
if(emptyCode === 8206)
{
//Remove all invisiable empty characters
cleanDate =(new Date()).toLocaleString().replaceAll(String.fromCharCode(emptyCode),'');
}
Extension Method can be found from below post.
How to replace all occurrences of a string in JavaScript?

maybe this solution can help (in dd.mm.yyyy format)
var curDate = new Date().toLocaleString().split(',')[0];

Related

why I can't create a new Date() from given string?

I'm using moment.js to find a time in different timestamp.
I wrote a simple javascript:
$(function () {
var timestamp = 1443556318; //GMT Tue, 29 Sep 2015 19:51:58 GMT
var today2 = moment.unix(timestamp).tz('America/New_York').toString();
today = new Date(today2);
alert(today2);
alert(today);
var hh = today.getHours();
alert(hh); //why it shows me 21 instead of 15?
});
and seems like this line today = new Date(today2); does not work properly.
Can you help me with that?
http://jsfiddle.net/b8o5cvdz/3
It doesn't work because, you use the following constructor
new Date(dateString);
where the
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
If you want to all the possible constructors, please have a look here.

Spit up date after converting it to a string

I have a date in milliseconds that I convert to a readable date. Then I covert it to a string so I can split it up and break it down to use the parts I need. The problem is when I break it down by space, it breaks down each character by itself and does not split it up where there's a space. Can anybody explain why and what I'm doing wrong?
here's my code:
var formattedDate = new Date(somedateMS);
var formattedDateSplit = formattedDate.toString();
formattedDateSplit.split(" ");
console.log(formattedDateSplit); // Mon May 18 2015 18:35:27 GMT-0400 (Eastern Daylight Time)
console.log(formattedDateSplit[0]); // M
console.log(formattedDateSplit[1]); // o
console.log(formattedDateSplit[2]); // n
console.log(formattedDateSplit[3]); // [space]
console.log(formattedDateSplit[4]); // M
console.log(formattedDateSplit[5]); // a
console.log(formattedDateSplit[6]); // y
How can I split it up so I can get rid of the day of the week, and just have the May 18 2015 18:35:27 into 4 separate values? (May, 18, 2015, 18:35:27)?
I've done this before and not sure why this time it's splitting it up by character.
Thank you!
You're setting formattedDateSplit to the whole Date string, unsplit:
var formattedDateSplit = formattedDate.toString();
Then you do this, which is probably a typo:
formattedSplit.split(" ");
since that's the wrong variable name; what you probably meant was:
formattedDateSplit = formattedDateSplit.split(" ");
You're getting individual characters because the subsequent code is just indexing into the string itself, not the split-up version of the string. The .split() function returns the array, so you have to assign it to something; it does not modify the string.

how get month from a string in javascript

i have a date in string like this: var myDateStr='1431451872338.00';
i want, getMonth() from this format date, i do:var date = new Date(myDateStr); but always return invalid date.
and the method getMont() always return NaN, if I put this: var date = new Date(1431451872338.00); this return the date correct but with my string not
my var myDateStr get the value from json and is variable, if someone can help me thank you very much in advance, i hope do understand
This works fine for me. You just need to be sure you're inputing a number, not a string.
var number = parseInt("1431451872338.00");
var date = new Date(number); //Tue May 12 2015 12:31:12 GMT-0500 (CDT)
var month = date.getMonth(); // 4
A Date object cannot be instantiated with a string. You better 1st transform your string into an Int and then ask for month:
var myDateStr='1431451872338.00';
var date = new Date(parseInt(myDateStr, 10));
alert(date.getMonth());
Could you use parseInt and do something like this:
var myDateStr = '1431451872338.00';
var myDateInt = parseInt(myDateStr, 10);
var myDate = new Date(myDateInt);
When you're passing in a date string to the javascript date object, it needs to be in the format "yyyy/mm/dd" or something like "January 10, 2014". What you're passing is the number of milliseconds since January 1, 1970, which is only accepted by the date object as a number. You need to change the type of your input variable.
Please make sure to research carefully before answering questions - the answer to your question is clearly stated on many date references like this one.
One Liner
var month = date.getMonth(Date(parseInt("1431451872338.00")));

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

How to get clients Time zone in JavaScript?

who can write a function to get clients Time zone,return value like:EDT EST IST and so on
toTimeString() method give time with the timezone name try out below...
var d=new Date();
var n=d.toTimeString();
ouput
03:41:07 GMT+0800 (PHT) or 09:43:01 EDT
Demo
or
Check : Automatic Timezone Detection Using JavaScript
download jstz.min.js and add a function to your html page
<script language="javascript">
function getTimezoneName() {
timezone = jstz.determine_timezone()
return timezone.name();
}
</script>
Use the Date().getTimezoneOffset() function and then build a hash table from this URL timeanddate to relate it to if you want to use the time zone value.
If you look at the result of calling the toString method of a Date object, you'll get a value that's something like "Tue Apr 24 2012 23:30:54 GMT+1000 (AUS Eastern Standard Time)". This will depend on what your system locale is set to.
From there you can match each capital letter within the parentheses.
var paren = new Date().toString().match(/\(.+\)/);
return paren ? paren[0].match(/([A-Z])/g).join("") : "";
The catch is that not every browser will include the parenthesised values.
If you're targeting Firefox with a known Java plugin, you can also exploit the java object in Javascript to create a new TimeZone (java.util.TimeZone) object based on a name (eg. "America/Los_Angeles"), then call the getDisplayName method to give you the name.
Use jstz to get the timezone name:
jstz.determine().name();
It returns timezone names (like 'America/New York') which you can then use with moment.js etc.
An offset (eg from a js Date object) is not enough, because it does not carry the additional DST information (you won't know whether the time needs to be adjusted for Daylight Savings and when).
get client time zone in javascript
output from -12 : +12
you can modify the output by change on this line -Math.round(a/60)+':'+-(a%60); Like -Math.round(a/60); you get //+2
var a = new Date().getTimezoneOffset();
var res = -Math.round(a/60)+':'+-(a%60);
res = res < 0 ?res : '+'+res;
console.log(res);
reference
This is the perfect answer to get full timezone of country-
var a = new Date($.now());
var regExp = /\(([^)]+)\)/;`enter code here`
var matches = regExp.exec(a);
alert(matches[1]);
this alert will give you output like indian standard time,american standard time,african standard time:
//$("#timezone option:contains(" + matches[1] + ")").attr('selected', 'selected');

Categories

Resources