Remove part of string but getting the deleted part as result - javascript

So, quick question (searched a lot in Google, but only found the answer which produces same response as below):
code:
var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

One method to achieve this would be to cut the start and end portions of the string then join them back together, something like this:
var teste = bookend('10/12/2017', 6, 7);
console.log(teste);
function bookend(str, start, end) {
return str.substr(0, start) + str.substr(end + 1);
}
An alternative would be to use a regular expression to match the parts of the date you want to keep and then join them back together:
var teste = '10/12/2017'.replace(/(\d{2}\/\d{2}\/)(\d{2})(\d{2})/, '$1$3');
console.log(teste);

You can simply rebuild a new string without the parts you don't want using multiple substr :
var test = '10/12/2017';
console.log(test);
var test_cut = test.substr(0,6)+test.substr(8,test.length);
console.log(test_cut)

Simple regular expression with replace. match 4 numbers, keep the last two.
var t = '10/12/2017';
console.log(t.replace(/\d{2}(\d{2})$/, '$1'))

var teste = '10/12/2017'.replace(/(?=....$)../, '');
console.log(teste);

You can use your custom function as -
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
year = year.toString().substr(2,2);
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return month + "/" + day + "/" + year;
}
var d = new Date('10/12/2017');
console.log(formatDate(d));

Right way would be to deal with Date object instead, it will ensure that you get right year always.
var newDate = new Date(teste);
console.log(((newDate.getFullYear()).toString()).substr(2,2));

Related

Convert MM/DD/YYYY to the format YYYYMMDD (javascript) [duplicate]

This question already has answers here:
How to change date format
(2 answers)
Closed 5 years ago.
I've been looking at many similar questions here, but the truth is I haven't been very successful, until I came across an answer that pleases me, but only almost does the trick:
function convertDate (userDate) {
// convert parameter to a date
var returnDate = new Date(userDate);
// get the day, month and year
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1;
var d = returnDate.getDay();
// converting the integer values we got above to strings
y = y.toString();
m = m.toString();
d = d.toString();
// making days or months always 2 digits
if (m.length === 1) {
m = '0' + m;
}
if (d.length === 1) {
d = '0' + d;
}
// Combine the 3 strings together
returnDate = y + m + d;
return returnDate;
}
It might be obvious, but the month and day in the output don't work 100% and I just don't know enough to understand why.
Output examples:
convertDate("12/31/2014");
"20141203"
convertDate("02/31/2014");
"20140301"
EDIT:
Replacing getDay for getDate seems to do the trick.
This answer works fine for my case too:
function convertDate (userDate) {
return userDate.substr(6,4) + userDate.substr(3,2) + userDate.substr(0,2);
}
It's because getDay returns a week day 0 to 6. You should use getDate instead.
Your second example is also a wrong date because February never have 31 days.
Perhaps you should try giving [momentjs] a shot. It really facilitate working with dates and transforming between formats using format.
Your code won't work properly even if you replace function getDay for getDate because you are using invalid date format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Fall-back_to_implementation-specific_date_formats
Generally if you need to handle only this one date format and it will not be changed in the future than your function can be as simple as:
function convertDate (userDate) {
return userDate.substr(6,4) + userDate.substr(3,2) + userDate.substr(0,2);
}
Change the code var d = returnDate.getDay(); to var d = returnDate.getDate();
function convertDate (userDate) {
// convert parameter to a date
var returnDate = new Date(userDate);
// get the day, month and year
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1;
var d = returnDate.getDate();
// converting the integer values we got above to strings
y = y.toString();
m = m.toString();
d = d.toString();
// making days or months always 2 digits
if (m.length === 1) {
m = '0' + m;
}
if (d.length === 1) {
d = '0' + d;
}
// Combine the 3 strings together
returnDate = y + m + d;
return returnDate;
}

Javascript number like time regex format

I'm receiving from my database time like hh:mm:ss, and in javascript i would like to put the time like hh:mm
this is my code
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
}
The function doesn't work well since i receive "false", any help?
Thanks
May be I am missing something in the question, but if you simply want to extract the hh:mm part from hh:mm:ss, then this should work:
// var time = "hh:mm:ss";
var time = "10:01:30";
var splitTime = time.trim().split(":"); // trim to remove any leading and trailing spaces
var formattedTime = splitTime[0] +":"+ splitTime[1];
console.log( formattedTime );
Couldn't you just do the following?:
function formatTime(time) {
var array = time.split(':');
return array[0] + ':' + array[1];
}
The other answer (using split) is undoubtably the easier way to do this.
However, if you're wondering why your regex was not matching, it is because your regular expression was looking for the first (hh) block, and then the second (mm) block, but was then expecting whitespace after that until the end of the line - no allowance for the ss part.
I changed this rather heavy-handedly to allow anything after the mm part until the end of the line. see below.
Also, if you're wondering why your formatTime function returns undefined its because you forgot to return result
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d).*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
return result;
}
I would consider working with native Date object to do your formatting. This will do a few things for you:
Automatically validate the time value that is being input. No need for regex to do this. Either the input string is valid and the function works, or it is invalid and the function returns NaN.
Give you flexibility in how you work with the value. Need to convert time zones, convert to Unix timestamp, etc.? These are built in methods on Date object.
Gives flexibility on input values. You could potentially you other string input types here if needed as long as they can allow for instantiation of valid Date object. You need to modify regex to allow for multiple input types or anything like that.
Using this approach, example code might look like:
function stripSecondsFromTimeString(time) {
// create data object representing current date
// the date is not really important here other than allowing
// you to format a fully valid Date object with your time fragment
var day = new Date();
var dateInput = day.toDateString() + ' ' + time;
var date = new Date(dateInput);
// validate we were able to get useful Date object
if(isNaN(date.getHours())) {
return NaN;
}
// log out some values so you can see how you might more fully work with Date object
console.log(date.toString());
console.log(date.getDate());
console.log(date.getHours());
console.log(date.getMinutes());
// prepare to return string
var hours = '' + date.getHours();
if(hours.length === 1) {
hours = '0' + hours;
}
var minutes = '' + date.getMinutes();
if(minutes.length === 1) {
minutes = '0' + minutes;
}
return hours + ':' + minutes;
}
// Usage examples
// your input time fragment
var inputTime = '10:01:30';
var formattedTime = stripSecondsFromTimeString(inputTime);
console.log(formattedTime);
// example failure case
var invalidTime = 'foo';
console.log(stripSecondsFromTimeString(invalidTime));

How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript

How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript
<script type="text/javascript" language="javascript">
function disptextbox() {
var d = new Date();
var x = document.getElementById("ddlweeklist").value;
switch (x)
{
case "1":
document.getElementById("txtstart").value = d.toDateString();
document.getElementById("Txtend").value = d.toDateString();
break;
case "2":
var firstday = new Date(d.setDate(d.getDate() - d.getDay()));
var lastday = new Date(d.setDate(d.getDate() - d.getDay() + 6));
document.getElementById("txtstart").value= firstday.toDateString();
document.getElementById("Txtend").value = lastday.toDateString();
break;
case "3":
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.getElementById("txtstart").value = firstDay.toDateString();
document.getElementById("Txtend").value = lastDay.toDateString();
break;
case "4":
var firstd = new Date(d.getFullYear(), 0, 1);
var lastd = new Date(d.getFullYear(), 11, 31);
document.getElementById("txtstart").value = firstd.toDateString();
document.getElementById("Txtend").value = lastd.toDateString();
break;
}
}
</script>
in this code of implementation I want the date format to be in dd/mm/yyyy format ...I will be glad if any one help me over this this function call occurs on the drop down change especially...I am ok with functionality of the code but not comfortable in handling with DATE FUNCTIONS...
so please suggest me where I can get good examples for implementing date functions...in javascript
You can do this if you want dd/mm/yyyy format date:
new Date().toISOString().substr(0,10).replace(/(\d{4})-(\d{2})-(\d{2})/g,"$3/$2/$1");
I've written a couple of prototypes for dates than you may find useful:
Date.prototype.dateStr=function(split){
split=split===undefined?"-":split;
var output=parseInt(parseInt(this.getMonth())+1).toString().toLength(2);
output+=split;
output+=this.getDate().toString().toLength(2);
output+=split;
output+=this.getFullYear().toString().toLength(4);
return output;
}
Date.prototype.FOM=function(){
return new Date(this.getFullYear(),this.getMonth(),1);
}
String.prototype.toLength=function(len,fill){
fill=fill===undefined?"0":fill;
var outStr=this.toString();
while (outStr.length<parseInt(len)){
outStr=fill+outStr;
}
return outStr;
}
Technically, the 3rd one is a string prototype, but whatever. new Date().FOM() will give you a javascript date object for the first day of whatever month you pass it. new Date().dateStr("/") will give you a string - mm/dd/yyyy format - with separators as whatever you pass it, default "-".
That last one will take a string and make it a certain length by prepending the 'fill' - default '0'.
You could try with this function:
function toDateString(mydate) {
var day = mydate.getDate();
var month = mydate.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + mydate.getYear();
}
You could then use it this way:
alert(toDateString(firstday)); // I'm using alert just for demonstration purposes
Here is a DEMO you could fiddle with.
EDITED: Learning from #Helpful's answer below, my above function could be used as a prototype to better fit the way you wrote up your code like this:
Date.prototype.toDateString=function() {
var day = this.getDate();
var month = this.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + this.getYear();
}
so you could call it this way:
alert(thedate.toDateString()); // This is how you used it, if I understood it well.
Here is a DEMO of that.
Pass any data format
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
hope this will help you sure.....

HTML5 Date Validation

I'm looking to implement validation for a mobile site, where I have two input fields and I would like the first to validate the value is no later than todays date, and the second to validate it is no later than a one year in advance of the first value.
E.g
First Value = 26/11/2013
Second Value can not contain a value later than 26/11/2014
Is this possible?
I like moment.js. It makes it easier to deal with dates and times.
First, let's make sure a day "is before tomorrow". This will depend a bit upon what the definition of tomorrow is.
var m = moment("26/11/2013", "MM/DD/YYYY");
// tomorrow this time
var t = moment().add("days", 1);
// tomorrow start of day
var tomorrow = moment([t.year(), t.month(), t.date()]);
if (m.lessThan(tomorrow)) {
// today!!! (or before)
}
Similarly, the same approach can be used for a year from now. It's likely fine enough to not care about the time component in this case, and I've slogged on another day - but if it matters (e.g. looking for the start of the day), see the previous example.
var m = moment("26/11/2013", "MM/DD/YYYY");
var aYearFromNow = moment().add("years", 1).add("days", 1);
if (m.lessThan(aYearFromNow)) {
// still less than a year!
}
1) cache the elements.
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
2) The value of d1 and d2 are string data type. So split them and parse it to date format as below
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
Here the year is incremented by 1, based on the value in d1.
4) Again parse it back to string format (YYYY-MM-DD)
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
5) Set this as value for max attribute for d2
d2.setAttribute("max", maxi);
Finally add the below method to onblur event of d1.
function setMaxDate() {
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
d2.setAttribute("max", maxi);
}
JSFiddle
Better with javascript. You can I use HTML5 attribute type="date" but keep in mind it's barely supported.
You can use a Regex pattern like this /([0-9]{2})/([0-9]{2})/([0-9]{4})/, that is, two decimal digits, a slash, two more decimal digits, a slash and four decimal digits, everything grouped separately (group 1 = day, group 2 = month, group 3 = year). You would test for this pattern in a event, (I would suggest onchange, since you mentioned mobile) and also check if the numbers are within a valid range (e.g. day < 32, month < 13, year < currentYear-1).

Is there a way to increment time using javascript?

So I am storing times as '01:30:00'. I have a start time and a date time dropdown. I want the dropdown to be set to the start time + 1hr. Is there a way to add the time via javascript or jquery?
Here's my current code:
$(".start_time").change(function(){
$(".end_time").val($(this).val());
});
Try this:
find the selected index of the start time
bump it up by 2 to find your end time index (given that you've got half hour increments)
use the mod operator % to wrap back to index 0 or 1 (for 00:00 and 00:30 respectively)
$(".start_time").change(function(){
var sel =$(this).attr('selectedIndex');
var endIdx = (sel + 2) % 48; // 47 is 23:30, so 48 should go back to index 0
$(".end_time").attr('selectedIndex', endIdx);
});
Try it out on JSBin.
There are two separate problems here: the first is parsing out the time from your .start_time input, and the second is incrementing it to be an hour later.
The first is really a string-manipulation exercise. Once you have parsed out the pieces of the string, e.g. via a regex, you could either turn them into a Date instance and use setHours, or you could just manipulate the components as numbers and them reassemble them into a string in the format you desire.
An example of this might be as follows:
var TIME_PARSING_REGEX = /([0-9]{2}):([0-9]{2}):([0-9]{2})/;
function padToTwoDigits(number) {
return (number < 10 ? "0" : "") + number;
}
$(".start_time").change(function () {
var stringTime = $(this).val();
var regexResults = TIME_PARSING_REGEX.exec(stringTime);
var hours = parseInt(regexResults[1], 10);
var newHours = (hours + 1) % 24;
var newHoursString = padToTwoDigits(newHours);
var minutesString = regexResults[2];
var secondsString = regexResults[3];
var newTimeString = newHoursString + ":" + minutesString + ":" + secondsString;
$(".end_time").val(newTimeString);
});
Basic example...
var date = new Date();
var h = date.getHours() + 1;
var m = date.getMinutes();
var s = date.getSeconds();
alert('One hour from now: ' + h + ':' + m + ':' + s);
Demo: http://jsfiddle.net/fBaDM/2/
After you parse you date/time string, you can use methods such as .setHours in your date object (more info at Mozilla Developer Center).
I highly recommend the DateJS library for working with date and time. I'm sure it'll be very handy for you.
protip: try to avoid replacing JavaScript with "jQuery markup"; it's all JS, after all. :)

Categories

Resources