I have a date string that is created by adding the following pieces:
var dateString = d + "/" + m + "/" + y;
The other variables are created previously in my code as being fetched from an internal web page (d = day, m = month, y = year).
This works fine so far.
How can I achieve that a leading zero is added to them if d and/or m consist of only digit ?
E.g. if d = 1 then it should become 01 and the same for m.
Many thanks in advance for any help with this, Tim.
I think it must be done manually.
var dateString = (d < 10? "0": "") + d + "/" + (m < 10? "0": "") + m + "/" + y;
There are some date formatting libraries/jQuery plugins around, but if this is all you need, they would be an overkill for that.
dateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
will add leading zeros to all lonely, single digits
Try following
var d_str = ("00" + d).slice(-2);
var m_str = ("00" + m).slice(-2);
var dateString_formatted = d_str + "/" + m_str + "/" + y;
Related
I am trying to generate a random string in javascript in the form [40 Alfanumeric charactors] [Date & Time] [Constant Organization Number] and so far this is what I have achieved.
function randString(x) {
var s = "";
var today = new Date();
var date = today.getFullYear() + '' + (today.getMonth() + 1) + '' + today.getDate();
var time = today.getHours() + "" + today.getMinutes() + "" + today.getSeconds();
var dateTime = date + ' ' + time;
var esd = " TSL12001749";
while (s.length < x && x > 0) {
var r = Math.random();
s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)));
}
return s + dateTime + esd;
}
document.getElementById("foo").value = randString(40);
<textarea id='foo' style='width:100%;height:200px'></textarea>
I can't seem to have the alphabet characters in the random string uppercased and also strip off the first two characters in the year value. ie 2021, should read 21. Insights are highly appreciated.
s.toUpperCase() would solve the uppercase.
var date = String(today.getFullYear()).substring(2, 4)+''+(today.getMonth()+1)+''+today.getDate();
to get the substring of the year.
I have a datetime that looks like this:
2017-04-17 18:26:03
How can I convert this to this format using javascript or jquery:
17/04/2017 18:26
I found this question which I thought might help me but the answers are converting a timestamp but mine is not a time stamp.
How to convert a DateTime value to dd/mm/yyyy in jQuery?
You can use simple string and array manipulation.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = `${parts[2]}/${parts[1]}/${parts[0]} ${parts[3]}:${parts[4]}`;
console.log(wanted);
Additional: If you don't have an environment that supports Template Literals then you can write it like this.
const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = parts[2] + '/' + parts[1] + '/' + parts[0] + ' ' + parts[3] + ':' + parts[4];
console.log(wanted);
You could use a regular expression within a replace call:
input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
var input = '2017-04-17 18:26:03';
var result = input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');
console.log(result);
Explanation
^: match start of the string.
(\d+): capture group that matches digits. A captured group can be back-referenced with $1 for the first group, $2 for the second ... etc. in the second argument.
:\d+$: match a colon followed by digits and the end of the string ($): as this is not captured, this part (seconds) will be omitted in the result.
try to create a function that format your date. here is an example that i wrote.
function formate(date) {
if (typeof date == "string")
date = new Date(date);
var day = (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
var month = (date.getMonth() + 1 <= 9 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "/" + month + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes();
return dateString;
}
console.log(formate("2017-04-17 18:26:03"));
This will do the work:
var timestamp = Date.parse('2017-04-17 18:26:03'); // 1492467963000
var date = new Date(timestamp).toJSON(); // "2017-04-17T22:26:03.000Z"
var dateStr = date.slice(0, 10).split("-").reverse().join("/") // "17/04/2017"
.concat(' ')
.concat(date.slice(11, 16)); // "22:26"
console.log(dateStr)
"17/04/2017 22:26"
I want to split a time string in an with hours minutes and ampm seperately.
When I tried it for English time strung with below code :
var time = "3:20 PM";
var patternParsed = time.replace(new RegExp("(\\W", "g")," ").split(" ");
o/p for patternParsed is 3,20,PM
but similar i want to do for korean time string
When I try the above regular expression for korean time string it does not works
var koreanTime = new Date().toLocaleTimeString('ko-KR');
document.writeln("\nKoreanTime : "+koreanTime);
var patternParsed = koreanTime.replace(new RegExp("(\\W", "g")," ").split(" ");
document.writeln("\nparsed pattern : "+patternParsed);
Can someone please help me with this hiw can I split timeString of different locales?
To get a standardized output of hours,minutes,[AM|PM] considering the locale adds an unnecessary complexity, it you already have the Date object, you can use it to generate the value:
var time = new Date();
if (time.getHours() < 12) {
var patternParsed = time.getHours() + "," + time.getMinutes() + ",AM";
} else {
var patternParsed = (time.getHours() - 12) + "," + time.getMinutes() + ",PM";
}
var koreanTime = time.toLocaleTimeString('ko-KR');
document.writeln("\nKoreanTime : " + koreanTime + "\nparsed pattern : " + patternParsed);
I want to get date from input which format is dd-mm-yyyy when this is set via Bootstrap Date Picker and base on this date calculate end of the week. Somehow I get some weird results.
$('#date-start').on('changeDate', function(){
var objThs = $(this);
if(objThs.parent().is('.reportDateWeeks')){
var arrDateEl = objThs.val().split("-"),
datStartDate = new Date(arrDateEl[2], arrDateEl[1] -1, arrDateEl[0]),
datEndDate= new Date(datStartDate.setDate(datStartDate.getDate()+7)),
datEndDateFormated = datEndDate.getDate() + '-' + datEndDate.getMonth() + 1 + '-' + datEndDate.getFullYear();
console.log('start ' + objThs.val());
console.log('end' + datEndDateFormated);
}
});
e.g. if I chose 04-05-2014 then console returns me:
start 04-05-2014
end 11-41-2014
I see two problems.
You switched month and day in the result.
You should add parentheses around datEndDate.getMonth() + 1. Otherwise the 1 will be added as a string, not a number (producing the 41 in your example).
So the fixed could would look like:
var datEndDateFormated = (datEndDate.getMonth() + 1) + '-'
+ datEndDate.getDate() + '-'
+ datEndDate.getFullYear();
Ok I found solution...
datEndDateFormated = datEndDate.getDate() + '-' + datEndDate.getMonth() + '-' + datEndDate.getFullYear();
I was so blind.. sory about that
Use parseInt method to convert string to integer and then +1 to it.
datEndDateFormatted = datEndDate.getDate() + '-' + parseInt(datEndDate.getMonth() + 1) + '-' + datEndDate.getFullYear();
I have a jQuery script which returns the current date into a text box. However, when a month with only one digit is displayed (e.g. 8) I want it to place a 0 before it (e.g. 08) and not place a 0 before it if it has 2 digits (e.g. 11).
How can I do this? I hope you can understand my question. Here is my jQuery code:
var myDate = new Date();
var prettyDate =myDate.getDate() + '' + (myDate.getMonth()+1) + '' + myDate.getFullYear();
$("#date").val(prettyDate);
( '0' + (myDate.getMonth()+1) ).slice( -2 );
Example: http://jsfiddle.net/qaF2r/1/
I don't like so much string concatenation:
var month = myDate.getMonth()+1,
prettyData = [
myDate.getDate(),
(month < 10 ? '0' + month : month),
myDate.getFullYear()
].join('');
You can use something like:
function addZ(n) {
return (n < 10? '0' : '') + n;
}
var myDate = new Date();
var newMonth = myDate.getMonth()+1;
var prettyDate =myDate.getDate() + '' + (newMonth < 9 ? "0"+newMonth:newMonth) + '' + myDate.getFullYear();
$("#date").val(prettyDate);
There are a number of JS libraries that provide good string formatting. This one does it c# style. http://www.masterdata.dyndns.org/r/string_format_for_javascript/
(myDate.getMonth() + 1).toString().replace(/(^.$)/,"0$1")
I love regex :)