is there any way to parse date in string using Datejs? - javascript

I came across Datejs recently and found it very useful. However I could not figure out if there is a way to parse a string and extract only date part from it using the same.
For example, if there is a string >> "I will start exercise from next Monday."
Then it should parse the string, extract 'next monday' from it and convert it into date and give me the result.
How can it be implemented?
Thanks :)

You can write some RegEx for that. That would be the easiest way. 'next' will be a keyword in that case. A simple function can lookup the current weekday and return the date of the next monday. Should not that complicated.
Edit:
You can do something like this:
var pattern = /^([\w\W.]*)(next){1}([\sa-zA-Z]*)/;
while (result = pattern.exec(yourTextVariable) != null){
// read the data as you need from the result array
}
The Pattern above expecting a white space then the keyword next and will red the next word if it only has alpha-letters. (please note that the RegEx is untested and may need some refactoring to fit your needs. You may take a look at this page to do this: javascriptkit.com)

Related

Validating Date Time In Javascript

I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.

Remake json from object to array?

I'm so lost in space right now. I've sat for like 2-3h to find a solution to this problem but i just keep failing. Maybe i've gone blind or something. I hate asking for help but i really need it right now.
I have a json-response from a page wich is in this format:
[Object { timestamp="2015-01-04 21:05:16", value="25.4"},
Object { timestamp="2015-01-04 21:10:27", value="25.3"},
Object { timestamp="2015-01-04 21:15:38", value="28.7"},
Object { timestamp="2015-01-04 21:20:49", value="33.5"}]
And i need for it to look like this:
[ [1183939200000,40.71],
[1184025600000,40.38],
[1184112000000,40.82],
[1184198400000,41.55],
[1184284800000,41.18],
[1184544000000,41.06]]
I have tried soo much stuff and i feel so stupid asking for this because its probably the easiest thing in the world.
Thank you in advance!
Edit:
Apparently what Im getting back from the call is:
[{"timestamp":"2015-01-04 21:05:16","value":"26.9"},
{"timestamp":"2015-01-04 21:10:27","value":"27.1"},
{"timestamp":"2015-01-04 21:15:38","value":"24.8"},
{"timestamp":"2015-01-04 21:20:49","value":"21.4"},
{"timestamp":"2015-01-04 21:26:01","value":"19.6"}]
I got the "object" one when i console.debug:ed it. Dont know if this makes any difference or not.
Thanks
Assuming that the second value in the array should be equal to the value member of the object:
arr = arr.map(function(obj) {
return [
Date.parse(obj.timestamp.replace(' ', 'T')),
+obj.value
];
});
The Date.parse function converts a string like "2015-01-04T21:05:16" to a JavaScript timestamp (ISO 8601 format). That's why your current format needs to be changed slightly.

Convert European price to another format

I'm trying to convert several European price formats to other formats. The European format is like this:
€1.795,00
I need to convert it to
€1,795.00
I'm using this script http://josscrowcroft.github.io/money.js/ to convert currencies from one to another. However when when it reads something like €1.795,00, it thinks its €1.79 which is problematic.
Is there a method which would convert any decimals to dots and vice versa? Or is there some other alternative method to achieve what I need.
There might be a cleaner solution but this is the easy one:
str.replace(",",";");
str.replace(".",",");
str.replace(";",".");
str = "€1.795,00";
str = str.replace(",",";").replace(".",",").replace(";",".");
Now, str = "€1,795.00";
str = str.replace(",",";").replace(".",",").replace(";",".");
Now, str = "€1.795,00";
Thanks for the reply everyone, actually I found the solution I was looking for. Here, for anyone else looking for the answer to this.
I'm using money.js as mentioned above to convert currencies and it so happens another script called accounting.js is also necessary if you want to format currencies.
http://josscrowcroft.github.io/accounting.js/
If you have something like €1.700,00, use method accounting.unformat from accounting.js and you'll get this 1700
Then simply convert it with money.js :)
btw, the function explanation is near the bottom of the link

Regex: find whatever comes after one thing before another thing

I want to find anything that comes after s= and before & or the end of the string. For example, if the string is
t=qwerty&s=hello&p=3
I want to get hello. And if the string is
t=qwerty&s=hello
I also want to get hello
Thank you!
\bs=([^&]+) and grabbing $1should be good enough, no?
edit: added word anchor! Otherwise it would also match for herpies, dongles...
Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.
jQuery has the query object for that (see JavaScript query string)
Or you can google a bit:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
looks useful; for example with
http://www.bloggingdeveloper.com?author=bloggingdeveloper
you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.
You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:
(?<=s=)(.*)(?=&)
In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).

Parse ONLY a time string with DateJS

I'm using the excellent (but large) DateJS library to handle dates and times in my webapp. I just came across something that I'm not sure how to handle.
I want my users to be able to enter Time strings only, without a date, but they should be able to enter it in any manner they please. For instance:
5:00 pm
17:00
5:00pm
5:00p
5p
etc.
Using Date.parse(value) converts these strings into a full date, which is exactly what I want. However, it also allows the user to enter any other part of a date string, such as:
sat 5pm
1/1/2010 5pm
etc.
I'm trying to use DateJS to validate an input field for a time value. Something like:
function validateTime(value) {
return Date.parse(value) !== null;
}
Is there a way to use DateJS features to solve this? There are other SO questions that provide solutions, but if DateJS has a way to do this, I don't really want to add more custom code to my app to do this.
Shortly after asking my question, I discovered that Date.parseExact() can take an array of format strings. Somehow I'm missed that. I managed to get something working with the following code:
function validateTime(input) {
return Date.parseExact(input, [
"H:m",
"h:mt",
"h:m t",
"ht","h t"]) != null ||
Date.parseExact(input, [
"h:mtt",
"h:m tt",
"htt","h tt"]) != null;
};
Note that some formats don't seem to be able to be included together at the same time, which is why I split them into two separate parseExact() calls. In this case, I couldn't include any string that contained a single t in it with format strings that contained a double tt in it.
The additive approach seems cumbersome. Takes away the beauty of DateJS in my opinion. I needed the same solution and decided to just sneakily append the date in front of my input string before parsing with DateJS:
var parsed = Date.parse(Date.today().toString('M/d/yyyy') + ' ' + this.value);
if (parsed) {
alert(parsed.toString('h:mm tt'));
}
Now DateJS will not be sniffing around for any of its date-part parsing patterns, as you have already subbed it in.
Hope this helps someone!

Categories