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..
Related
This is my data format:
"21/03/2019 19:18"
The problem i am facing is, when ever if i am dealing with date or time there is an issue with the month ( it has 03 instead of 3 ). I am using library called date-fns. And also i have tried with the help of javascript date objects without using library, but no luck still the month should not have zero in-front of it.
So, how to remove the "0" in-front of "3", and one more problem is how to do this conditionally , because when its Dec, i will be getting data as "21/12/2019 19:18". So, in this case , i should not remove "1" as its located in same position of "0" in previous scenario.
In other words, i want to remove "0" by checking if there is "1" presented in that position or index, if presented then remove else remove "0"
How to achieve this.
I tried the below code:
const d = new Date(2019,03,21)
But, its says legacy error. So when i removed "0" infront of "3" it works fine. Please help
I assume you get the data back as a string and you just want to remove leading zeros from the 2nd number only?
we can use .split to break up the string into parts, and then we can use parseInt to convert some string parts into numbers. that will turn the string "03" into the number 3
function removeleadingZerosFromDateString(str) {
//Break up the date string on the slashes and whitespace, so we have an array of all the parts
var parts = str.split(/\/|\s/);
console.log(parts);
//Assign each array item to a variable so we can see what is what
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parts[2];
var time = parts[3];
var meridian = parts[4];
return day+'/'+month+'/'+year+' '+time+' '+meridian;
}
var result = removeleadingZerosFromDateString("21/03/2019 19:18 PM");
console.log(result);
You said you were using date-fns, so I'll give an answer in that regard.
The current 1.x version doesn't support parsing strings in a custom format, but they are adding that to 2.x, and you can use the alpha release to try it today.
The syntax is:
var date = parse(dateString, formatString, baseDate, [options]);
See the documentation for the parse function in version 2.0.0-alpha.27.
In your case, it would be like this:
var date = parse("21/03/2019 19:18", "MM/dd/yyyy HH:mm", new Date());
Lastly, if you want to use a library for this but don't want to experiment with an alpha, you can either wait for Date-fns 2.0 to become final, or you can try Luxon or Moment - both of which already have this functionality (though Moment uses a slightly different token format "MM/DD/YYYY HH:mm").
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.
In IE 11, I'm getting funny results with ToLocaleDateString(). The string returned looks fine in the browser, e.g. "1/28/2014 11:00:46 AM", but then if I copy and paste that value into a plain text editor, it looks like this: "?1?/?28?/?2014 ?11?:?00?:?46? ?AM".
Interestingly, if I paste the text into a Microsoft product, it looks fine... The issue is that if you try to use the value programmatically to create a date, it's invalid. You can test this by just opening up a console in IE11 and creating a new date, using ToLocaleDateString() on it, and then trying to use the resulting string to create a new date in javascript or in the language of your choice (I'm using ASP.NET here...).
Am I doing something wrong, or is there some other way I'm supposed to be interacting with the javascript Date? How can I get rid of those funky symbols?
Edit:
Thanks to the comment below I was able to figure out what the unshown characters are, they're Left-To-Right marks. Depending on the editor I paste the values into and the encoding that the editor is set to use, the text will show up differently: sometimes with "?", sometimes without.
I fixed that with the following replace(/[^ -~]/g,'') as in
(new Date("7/15/2014").toLocaleString().replace(/[^ -~]/g,'')
The issue is that if you try to use the value programmatically to create a date, it's invalid.
...
Am I doing something wrong, or is there some other way I'm supposed to be interacting with the javascript Date?
Yes, you are doing it wrong. You shouldn't be using a function intended to format something for locale-specific human display and expect the output to be machine parsable. Any of the output of toLocaleString, toLocaleDateString, or toLocaleTimeString are meant for human-readable display only. (As Bergi clarified in comments, toString is also meant for human display, but ECMA §15.9.4.2 says it should round-trip)
You are likely getting the LTR markers because your display locale is RTL. Besides this, consider that the locale will always affect the output. Perhaps your locale uses dd/mm/yyyy formatting instead of mm/dd/yyyy formatting. Or perhaps your locale requires Asian or Arabic characters. These are all considerations when determining a display format, but are never appropriate for machine parsing.
Also consider that the ECMAScript specification does not define any particular formatting rules for the output of these methods, and different browsers will yield different results.
If the intent is anything other than to display to the user, then you should use one of these functions instead:
toISOString will give you an ISO8601/RFC3339 formatted timestamp
toGMTString or toUTCString will give you an RFC822/RFC1123 formatted timestamp
getTime will give you an integer Unix Timestamp with millisecond precision
All of the above will return a UTC-based value. If you want the local time, you can either build your own string with the various accessor functions (getFullYear, getMonth, etc...), or you can use a library such as moment.js:
This uses moment.js to return an ISO8601 formatted local time + offset from a date:
moment(theDate).format() // ex: "2014-08-14T13:32:21-07:00"
function FixLocaleDateString(localeDate) {
var newStr = "";
for (var i = 0; i < localeDate.length; i++) {
var code = localeDate.charCodeAt(i);
if (code >= 47 && code <= 57) {
newStr += localeDate.charAt(i);
}
}
return newStr;
}
Only returns digits and the / character. Seems to make this work:
new Date(FixLocaleDateString(new Date("7/15/2014").toLocaleString()));
Returns the correct date. Without the call to FixLocaleDateString(), the result would be an invalid date.
For completeness, answer form:
On my system, IE 11's Date object's method toLocaleDateString results in "7/6/2014" when run in the Console which is represented as the following bytes:
00000000 22 e2 80 8e 37 e2 80 8e 2f e2 80 8e 36 e2 80 8e |"â.Z7â.Z/â.Z6â.Z|
00000010 2f e2 80 8e 32 30 31 34 22 |/â.Z2014"|
The non-printables are 0xe2 0x80 0x8e throughout which is the UTF-8 representation of Unicode Code Point U+200E. Which is, as the comments above say, the LEFT-TO-RIGHT MARK.
This JSFiddle doesn't seem to have trouble using the value returned from toLocaleDateString() to get back to a date. At least in my IE 11.0.9600.17239 with Update Version 11.0.11 (KB2976627). So maybe only the console adds the extra characters?
var startDateConverted = new Date(start).toLocaleString().replace(/[^A-Za-z 0-9 \.,\?""!##\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')
if you also want to remove time use .split(' ').slice(0, -1).join(' ');
I'm looking to target the following string using jQuery. Specifically, I need to wrap it in a strong tag for styling purposes. I can't change the source data. My regex-fu is pathetic. Any suggestions?
Nov 18, 2013, 4pm CST:
Thanks guys - these are excellent answers. I should have been slightly more specific - I need to match all occurrences of this format within a collection, e.g.:
$('.admin-comments').match(/[A-Z]{1}[a-z]{2}\s[0-9]{1,2},\s[0-9]{4},\s[0-9]{1,2}[a|p]m\s[A-Z]{3}/)
(I have a log of comments and I'm trying to wrap the timestamp in a strong element.)
Edit: Final Working Solution
var adminComment = $('.admin-comments');
if (adminComment.length) {
var adminCommentTxt = adminComment.text();
var formatCommentTimestamp = adminCommentTxt.replace(/([A-Z]{1}[a-z]{2}\s[0-9]{1,2},\s[0-9]{4},\s[0-9\s]{1,2}[ap]m\s[A-Z]{3}\:)/g, "<strong>$1</strong>");
adminComment.html(formatCommentTimestamp);
}
Here you go: /^[A-Z]{1}[a-z]{2}\s[0-9]{1,2},\s[0-9]{4},\s[0-9]{1,2}[a|p]m\s[A-Z]{3}\:$/
'Nov 18, 2013, 4pm CST'.match(/^[A-Z]{1}[a-z]{2}\s[0-9]{1,2},\s[0-9]{4},\s[0-9]{1,2}[a|p]m\s[A-Z]{3}\:$/)
["Nov 18, 2013, 4pm CST"]
Keep in mind that this regex is expecting the line to start and end with this date, if the date is contained within other text, remove the ^ from the start and the $ from the end.
Hope this helps.
To further explain the regex and hopefully ++ your "regex-fu"
[A-Z]{1} - match one upper case letter
[a-z]{2} - match two lower case letters
So far we are at Nov, Oct, Jan, etc.
\s - space
[0-9]{1,2} - a 1 (min) or 2 (max) digit number
, - literal comma
\s - space
[0-9]{4} - a 4 digit number (the year)
So now we have matched: Nov 18, 2013
, - literal comma
\s - space
[0-9]{1,2} - just like before, a one or two digit number
[a|p]m - 'a' or 'p' followed by an 'm'
Now we've matched: Nov 18, 2013, 4pm
[A-Z]{3} An upper case three character string
\: literal colon
That is the entire string.
Putting ^ at the beginning of the regex means the text we are matching against MUST begin with the pattern; similarly, the $ states that the text we are matching MUST end with the pattern.
Good luck!
Rob M's answer is perfectly valid, and a more generic version than mine and may be exactly what you're looking for. However, if you want to be more specific with your months and time zones this may be useful for you:
(Oct)?(Nov)?\s\d{1,2},\s\d{4},\s\d{1,2}(pm)?(am)?\s(CST)?(PST)?:
This will match all of:
Nov 18, 2013, 4pm CST:
Oct 8, 2011, 11am PST:
Nov 02, 1981, 2am PST:
Oct 31, 1843, 12pm CST:
If you needed more months, you simply add each one like so:
(Mmm)? where Mmm corresponds to the month you want to match.
Similarly if you need more time zones, you'd add them like so:
(ZZZ)? where ZZZ corresponds to the timezone you want to match.
Similar to Rob's answer, if your date string is the only thing on the line, you could add the /^ and &/ prefix & suffix.
what will be the regular expression of date format like '01-Aug-12'.
I have the date format of dd-M-y in asp.net application and want to validate it from asp.net regular expression validator control.
A very basic format check would be:
\d{2}-[A-Za-z]{3}-\d{2}
See for yourself here.
To actually validate, we need a day check like #Brijesh Gandhi suggested and then add a complete month list like this:
([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}
If you want to allow for lowercase months like aug, you can add the case-insensivity modifier ?i: like this...
([12]\d|0[1-9]|3[0-1])-(?i:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}
...but that will also allow a month like e.g. aUg - it might be most correct to only allow the first character to be upper- or lowercase.
([12]\d|0[1-9]|3[0-1])-([Jj]an|[Ff]eb|[Mn]ar|[Aa]pr|[Mm]ay|[Jj]un|[Jj]ul|[Aa]ug|[Ss]ep|[Oo]ct|[Nn]ov|[Dd]ec)-\d{2}
See this final version in action here.
Please note that this still will not detect invalid dates like 30-Feb-12. A regexp not accepting those special dates will be very long/ugly. Even using Javascript's Date.parse(...)/new Date(...) will not help detect those as it happily accepts the above mentioned, non-existant date, and return the 1st of March. So to be 100% correct, you need to either do complex coding yourself, or use a library like datejs.
Edit 1: Shortened #Brijesh Gandhi's day check a bit, updated Regexr link.
Edit 2: Remark on correctness.
Why regexp?
I would validate it using
DateTime.TryParse(...)
Anyway a basic form of regex could be
[0-3][0-9]-[A-Z][a-z][a-z]-[0-9][0-9]
which could be better than nothing.
This won't be too elegant, but if you want to use regex to validate dates, it is here:
The regex with explanation
(
(
31-(Jan|Mar|May|Jul|Aug|Oct|Dec)| # months with 31 days
(0[1-9]|[12]\d|30)-(Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)| # months with 30 or 31 days
(0[1-9]|1\d|2[0-8])-Feb # February up to 28th
)
-\d\d # any two digits represent the year
)|
(
29-Feb-([02468][048]|[13579][26]) # February 29th
)
This regex doesn't accept invalid dates like 00-Aug-00, 32-Aug-00 and 29-Feb-01 while accepting valid dates including leap days (29-Feb-04). Note that we assume 00 stands for year 2000, not 1900. So, we accepted 29-Feb-00 as leap day!
In one line:
See it in action:
((31-(Jan|Mar|May|Jul|Aug|Oct|Dec)|(0[1-9]|[12]\d|30)-(Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(0[1-9]|1\d|2[0-8])-Feb)-\d\d)|(29-Feb-([02468][048]|[13579][26]))
Case-insensitivity
In Javascript, add an i as second parameter:
var re = new RegExp(regexStr, "i");
In ASP.NET, use RegexOptions.IgnoreCase:
Regex re = new Regex(regexStr,RegexOptions.IgnoreCase);
Regular Expression is definitely not the way to go here. We could do a simple Date.Parse which returns NaN if the date is not valid.
var myDate = '01-Aug-12';
var isValidDate = !isNaN( Date.parse( myDate ));
try this regex
([1-2][0-9]|[0][1-9]|[3][0-1])-[a-zA-Z][A-Za-z][a-zA-Z]-[0-9][0-9]
00-aug-12 is not valid date according this regex [0-3][0-9]-[A-Z][a-z][a-z]-[0-9][0-9]
Here is regex for every combination of the date format dd-MMM-yy:
[0123][0-9]-[JFMASOND][aepuco][nbrylgptvc]-[0-9][0-9]
Note how the month part is overly strict, while you may still be able to supply an invalid date. Maybe it is better to try to parse the date and check whether it is valid.