trim a string containing time from date picker - javascript

I am using angular UI date picker to get the date. I save the date into a string variable. The problem is that I want the date to be trimmed out in a very specific format. I don't know regex, at all which I think is the right way to do this in javascript? Can somebody tell me the regex that I can write in a function that will trim the input to the specific output using native javascript only.
e.g.
Input:
Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time.
Output should be:
20-2-2015 00:00:00.
Thanks a lot!

<html>
<body>
<script language=javascript>
var txt='Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time';
var re1='.*?'; // Non-greedy match on filler
var re2='(20-2-2015)'; // DDMMYYYY 1
var re3='(\\s+)'; // White Space 1
var re4='(00:00:00)'; // HourMinuteSec 1
var p = new RegExp(re1+re2+re3+re4,["i"]);
var m = p.exec(txt);
if (m != null)
{
var ddmmyyyy1=m[1];
var ws1=m[2];
var time1=m[3];
document.write("("+ddmmyyyy1.replace(/</,"<")+")"+"("+ws1.replace(/</,"<")+")"+"("+time1.replace(/</,"<")+")"+"\n");
}
</script>
</body>
</html>

This should give you what you want:
var date = "Thursday sep 20-2-2015 00:00:00 GMT (+5:00) Pakistan Standard Time";
var expectedDate = date.match(/\d{1,2}-\d{1,2}-\d{4}\s\d{2}:\d{2}:\d{2}/g);

Related

How to format "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply mm.dd.yy using Google App Script>

I am trying to convert my date column from a google sheet from "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply 09.11.20. I tried this code but it does not convert and throws an error. Please advise:
var date1 = sheet.getRange('P2:P2').getValues(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yy");
What do I need to change here?
Try var date1 = sheet.getRange('P2').getValue()
getValues() returns a multidimensional array.
Since you want to get only cell P2 you should use
sheet.getRange('P2').getValue() instead.
assuming the latter returns a date object, this would probably work:
var date1 = sheet.getRange('P2').getValue(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy");
If the result you are getting is the day of yesterday, then try this:
var date1 = sheet.getRange('P2').getValue(); //my date field
var df = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy").split('.');
var date_formatted = `${df[0]}.${parseInt(df[1])+1}.${df[2]}`;

How to get date in d/m/y format using javascript date.js library?

I am trying to get next 30th date from a specified date using javascript library date.js. here is my code:
<script src="date.js">
var val = (document.formi.pack_val.value) * (30) ;
var d = Date.today().add(val).days();
document.formi.date.value = d;
</script>
However I'm getting output like this:
Tue Apr 28 2015 00:00:00 GMT+0530 (India Standard Time)
How to get output like this?
28/4/2015
You just need to use .toString('dd/MM/yyyy') like this:
<script src="date.js">
var val = (document.formi.pack_val.value) * (30) ;
var d = Date.today().add(val).days();
document.formi.date.value = d.toString('dd/MM/yyyy');
</script>
As standard JS does not support a (dd/mm/yyyy) format I'd recommend downloading and installing Date.js: https://github.com/datejs/Datejs
After which you should be able to reference
new Date().toString('M/d/yyyy')
where you have
.toString('dd/MM/yyyy');

How to convert string to date format in javascript?

How can convert a string to date format in java script.
I want to convert this string "Wed May 15 2013 11:30:00 GMT 0530 (IST)" into a date format.
Use Date.parse function
// create Date object from string
var d = new Date(Date.parse("Wed May 15 2013 11:30:00 GMT 0530 (IST)"));
var dateString = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
<script type="javascript">
var dateTime = new Date();
alert(dateTime.toString());
</script>
Here is the working Demo: Demo

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Javascript: Extract a date from a string?

I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );

Categories