How To parse timeString with different Locales? - javascript

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);

Related

Is there a way to have alphabet characters in uppercase in my javascript random string?

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.

Convert date to ISOString javascript server side?

i have a date with this format" 20/02/2018 14:40:00 CET" how can i convert it with the format ISOString, i tried this code but i haven't any result !!
function myFunction() {
var d = '20/02/2018 14:40:00 CET';
var n = d.toISOString();
document.getElementById("demo").innerHTML = n;
}
You need to create a new date instance before try use toISOString method, however correct date format is mm/dd/yyyy so try this :
var d = new Date("02/20/2018 14:40:00");
var n = d.toISOString();
console.log(n);
You need to split and re-assemble since European date format (20/02) is not parse-able
var d = '20/02/2018 14:40:00 CET',
parts = d.split(" "),
time = parts[1].split(":"),
dParts = parts[0].split("/");
+time[0]--; // CET is +1 - for more https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
var n = dParts[2] + "-" +
dParts[1] + "-" +
dParts[0] + "T" +
time[0] + ":" +
time[1] + ":" +
time[2] + ".000Z";
console.log(n);

Javascript: convert datetime to DD/MM/YYYY - Time?

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"

jQuery: add leading zeros to date string

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;

JavaScript AM/PM time comparison

Suppose I have 2 datetime variables:
var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";
I want to compare these 2 datetimes. How can I get Javascript to recognize whether the time is AM or PM?
I think Javascript will compare the time in 24 hours format. Do I need to convert the time to 24 hour format? Is that correct? Could someone please suggest the correct solution....
Just use straight javascript functions
var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";
var from = new Date(Date.parse(fromdt));
var to = new Date(Date.parse(todt));
alert(from);
alert(to)
if (from > to) alert("From");
else alert("To");
Once the date is parsed into date form, you can do what you like with it. And you can compare dates using the standard operator signs ( >, < etc)
I'm not sure what you need to do with them, but http://www.w3schools.com/jsref/jsref_obj_date.asp is an okay reference.
And heres a crappy sandbox with the above code http://jsfiddle.net/QpFcW/
and a better one that XX deleted :( http://jsfiddle.net/QpFcW/1/
Use this function
function get_time() {
var time_t = "";
var d = new Date();
var cur_hour = d.getHours();
cur_hour < 12 ? (time_t = "am") : (time_t = "pm");
cur_hour == 0 ? (cur_hour = 12) : (cur_hour = cur_hour);
cur_hour > 12 ? (cur_hour = cur_hour - 12) : (cur_hour = cur_hour);
var curr_min = d.getMinutes().toString();
var curr_sec = d.getSeconds().toString();
if (curr_min.length == 1) {
curr_min = "0" + curr_min;
}
if (curr_sec.length == 1) {
curr_sec = "0" + curr_sec;
}
$("#updatedTime").html(
cur_hour + ":" + curr_min + ":" + curr_sec + " " + time_t
);
alert(cur_hour + ":" + curr_min + ":" + curr_sec + " " + time_t);
}

Categories