Spit up date after converting it to a string - javascript

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.

Related

How to change a date to a string without losing the original formatting?

My date is 2022-01-19T13:00:56.000Z
I need to be able to replace some characters in this, so I need to convert it to a string.
However it loses its format if I use toString():
console.log(myDate.toString())
// output is Wed Jan 19 2022 21:00:56 GM +0800 (Hong Kong Standard Time)
I want to convert the date 2022-01-19T13:00:56.000Z to "2022-01-19T13:00:56.000Z".
How to accomplish this?
toISOString DOES produce a string you can manipulate
const date = new Date("2022-01-19T13:00:56.000Z")
console.log(date.toLocaleString());
// Add 6 hours to the time
date.setHours(date.getHours() + 6);
const isoString = date.toISOString();
// Intermediate result
console.log(isoString);
// Fix the offset
const ZPlus6 = isoString.replace("Z","+0600");
// Adjusted timestamp
console.log(ZPlus6);
// Produces the same date and time as original
console.log(new Date(ZPlus6).toLocaleString());

JavaScript new Date().toLocaleString() length

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];

How do I append the user's timezone to a string in Javascript?

I found some code here on Stack Overflow that does exactly what I want, which is to take a GMT time string and convert it to the local time on the user's browser. Awesome.
However, I'm stuck on what should be a very small thing. When I display the time, I want the user's current local timezone to display along with the time. The goal is to output a string that looks something like:
2014/02/19 15:12 (PST)
I've looked at the parameters for the Javascript Date() function, but, unless I'm blind, I don't see one that outputs the user's timezone. There's getTimezoneOffset(), which returns a number, but not the code for the timezone.
I've got all the rest of the time displaying fine, except for that last part where I want it to say PST (or GMT or JST or wherever the user is). Is there a way to do that?
It can be done creating a date and then performing some operations on it. If you take a look at format in which newly created Date object is created it is e.g. like:
Wed Feb 19 2014 07:29:26 GMT+0100 (Central European Standard Time)
Now you may simply take the whole name like:
var myDate = new Date();
var userTmzn = myDate.substring(myDate.lastIndexOf('(')+1).replace(')','').trim()
and this should give you this in userTmzn
Central European Standard Time
Now to make it neat and have an abbreviation you may try some more operations:
// Take the part with timezone name and strip it from trailing ')'
var fullName = myDate.split("(")[1].replace(")","");
// Split into words
var words = fullName.split(" ");
// Take just first letters
var timezoneCode = "";
for(i = 0; i < words.length; i++)
{
timezoneCode += words[i].charAt(0);
}
That should give you (following the same example) this in timezoneCode variable:
CEST
This is highly custom, not a ready solution. You should verify in the code that default date's toString() returns date in TIME FORMAT, you should test on various browsers, etc. This is just a clue.

append string with matched substring

Im having issues with formatting a string received from the Twitter API. Im using timeago plugin and returns NaN in IE 10. After hunting it down it seems to be because the time recieved is formatted like so:
Tue Apr 02 14:27:31 +0000 2013
instead of:
Tue Apr 02 14:27:31 2013 +0000
Anyone know a quick way of matching if this is present and then appending the string if it is?
regards
You can use splice and split method to achive this.
var time="Tue Apr 02 14:27:31 +0000 2013";
var arr = time.split(" ");
var year = arr.splice(arr.length-1,1);
arr.splice(arr.length-1,0, year[0]);
//console.log(arr.join(" "));
You can do this:
Var dateStr; // your date string
Var index = dateStr.indexOf('+');
If (index === dateStr.length-5) {
// you're in format two, what you wanted
}
The caveat is that this date has to come in the way you displayed it.
Using regular expressions you could use this:
var originalDate = "Tue Apr 02 14:27:31 +0000 2013";
// find the last two number blocks and swap them
var reformattedDate = originalDate.replace(/ (\+[0-9]+) ([0-9]{4})$/, "$2 $1");
This will switch the position of the last two number-blocks in the original date.
Also this method will not change dates that don't match the regular expression. If you get an originalDate that already has the format "2013 +0000" it will not be changed. ;)

regex javascript to add to expression

I have to write a few regexes. I did all except the following. I don't know how to add something via regex only.
Change this  9/28/2005  to  09.28.2005  (Am able to replace slashes with period but how to add leading zero to 9)
Change September 21, 2006 to 21. September 2006 (am able to replace , with . but how to change the order?)
Change 5:00 PM to i7:00 Uhr   (12 to 24 hour)?
1st Case (padding with zero):
result = subject.replace(/\b(\d)(?=[\/.])/ig, "0$1");
2nd Case (change order):
result = subject.replace(/\b(january|february|march|april|may|june|july|august|september|october|november|december) +(\d{2}), +(\d{2,4})\b/ig, "$2. $1 $3");
3rd case (12-24 hr)
As JavaScript RegEx engine does not support If-Then-Else Conditionals. So, it is hard and time-taking job to create a pure RegEx pattern for that purpose.
Hope this helps.
Just do the math manually... e.g. make a function GetTimeZoneOffset and go from there...
Return the timezone difference between UTC and Local Time:
var d = new Date()
var n = d.getTimezoneOffset();
The resulting value of n will be: 240
Add the difference and viola you have a real date which you can format what way you want..

Categories

Resources