I have this string:
var date = "3/2020";
I need the date in this format and adding a 0 if the month is less than 10:
var result = "2020-03";
I already did this:
var date = "3/2020";
var result = date.replace('/', '-');
console.log(result);
I just need a little help to know how could I add a 0 if the month is less than 10, and to change the order. Any Suggestion ?
I would suggest looking into moment.js
Then you can create a new date and set format and also set the wanted output format
const date = moment("3/2020", "MM/YYYY").format("YYYY-MM")
const date2 = moment("11/2020", "MM/YYYY").format("YYYY-MM")
console.log(date)
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Regex would help.
const input = "3/2020";
const [_, month, year] = /(\d+)\/(\d*)/.exec(input);
const output =`${year}-${month.toString().padStart(2, "0")}`;
console.log(output);
It can be done with a one-liner (which I have broken down into multiple lines to explain them) :
const date = "3/2020";
const dateFormatted = date
.split("/") // [ "3" , "2020" ]
.reverse() // [ "2020" , "3" ]
.map(d => /^\d$/.test(d) ? "0"+ d : d) // transforms "3" into "03" but leaves "2020" intact
.join("-"); // "2020-03"
console.log(dateFormatted)
Please use Array.map(), Array.split() and Array.reverse() functions.
Like this.
const date = "3/2020";
const result = date.split('/').map(val => val.length === 1 ? '0' + val : val).reverse().join('-');
console.log(result);
var date = "3/2020";
dateandmonth = date.split("/");
var event1 = new Date();
event1.setMonth(dateandmonth[0]-1);
event1.setYear(dateandmonth[1]);
MyDateString = (event1.getFullYear() + "-" + ('0' + (event1.getMonth()+1)).slice(-2));
I would never claim this is a clever way of doing it but, just for fun, you could manage everything using just String.prototype.slice() in a template string:
const input1 = '3/2020';
const output1 = `${(input1).slice(-4)}-${('0' + input1).slice(-7, -5)}`;
//-----------------------------------------^ prepend a '0' in case months < 10
const input2 = '11/2020';
const output2 = `${(input2).slice(-4)}-${('0' + input2).slice(-7, -5)}`;
// test
console.log(output1);
console.log(output2);
Obviously this works exclusively on the premises that you know for sure the input string format is consistent and predictable: 1 or 2 digits for the month, 1 separator character, 4 digits for the year.
I do not recommend using it in a real product, especially if the input string comes from an API and its format may change over time.
You can use date-fns library.
import { parse, format } from 'date-fns';
const convertDateFormat = (dateStr, oldFormat, newFormat) => {
let date = parse(dateStr, oldFormat, new Date());
return format(date, newFormat);
};
const date = new Date();
const formattedWithSlash = format(date, 'MM/yyyy');
console.log(formattedWithSlash); //'10/2021'
const changedFormat = convertDateFormat(formattedWithSlash, 'MM/yyyy', 'yyyy-MM');
console.log(changedFormat); //'2021-10'
Related
I need to convert string of format "14.12.22 15:17" to date in order to sort it by seconds. thank you in advance
const toTimestamp = (strDate) => {
const parsedDate = strDate.split(".");
const b = parsedDate[2].split(" ");
const string = `20${b[0]}-${parsedDate[0]}-${parsedDate[1]}T${b[1]}:00`;
const date = new Date(string).getTime();
console.log(string);
return date;
};
toTimestamp('4.12.22 15:17');
You want to use Date.parse() after converting the string to ISO 8601 format:
const datestrings = ["14.12.22 15:17", "14.12.22 15:16", "12.12.22 22:22"]
const toTimestamp = (strDate) => {
const parts = strDate.split(" ")
const d = parts[0].split(".");
const t = parts[1]
const string = `20${d[2]}-${d[1]}-${d[0]}T${t}`;
const date = Date.parse(string);
console.log(string, date);
return date;
}
const dateTimes = []
datestrings.forEach(d => dateTimes.push(toTimestamp(d)))
dateTimes.sort()
console.log(dateTimes)
var t = "14.12.22 15:17"
var ts = t.split(" ");
var tss = ts[0].split(".")
var tsss = []
tsss.push(tss[1] + ".")
tsss.push(tss[0] + ".")
tsss.push(tss[2] + " ")
tsss.push(ts[1])
tsss.join();
var d = new Date(tsss);
console.log(d.getTime()/1000);
You can use third-party libraries for parsing the date, e.g., moment.js is one of the famous ones.
Your code can simplified as
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
const momentDate = moment('14.12.22 15:17', 'YY.MM.DD HH:mm');
console.log(momentDate.toDate());
</script>
</body>
</html>
Once you have the object you can easily sort on the date object.
Using dayjs:
const dayjs = require('dayjs')
const customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)
const toTimestamp = (strDate) => {
return dayjs(strDate, 'DD.MM.YY HH:mm').unix()
}
I'm not sure why you are doing all the parsing and re-assembling into an ISO format manually? Without pulling in any libraries like suggested by #Manish Rawat you could do the parsing with a regex, might make it a bit more readable:
// as pointed out in the comments, this doesn't work as expected
// it will interpret the '4' as the month...
//console.log((new Date('4.12.22 15:17')).toISOString())
const toDate = function(str) {
const rex = /(?<day>\d+).(?<month>\d+).(?<year>\d+)\s+(?<hours>\d+):(?<minutes>\d+):?(?<seconds>\d+)?/;
const { day, month, year, hours, minutes, seconds } = (str.match(rex))?.groups || {
day: 0,
month: 0,
year: 0,
hours: 0,
minutes: 0,
seconds: 0
};
// console.log(str.match(rex)?.groups, year, month, day, hours, minutes, seconds);
return new Date(`20${year}-${month}-${day} ${hours}:${minutes}${seconds ? ':' + seconds : ''}`);
};
console.log(toDate('4.12.22 15:17'), toDate('4.12.22 15:17').getTime());
also, from there, what kind of sort are you planning to do? string based i assume? why not convert those dates to actual unix timestamps, e.g. number of seconds and compare those, so you won't have to deal with "weird" javascript string sorting things that might not yield the sort you are expecting?
So this is a new one to me. I've been working with this api and they returned a date in json format that looks like this
{
DateAdd: "/Date(1582936941390-0600)/"
}
not exactly sure how to convert this to a datetime like in the format below so I can actually do something with it.
2020-03-13 23:08:00
i have never seen this date format before! Thanks
Use moment.js to convert the date format
var data = {
DateAdd: "/Date(1582936941390-0600)/"
}
var datam = moment(data.DateAdd)
console.log(datam.format("YYYY-MM-DD HH:mm:ss")) // 2020-02-29 07:42:21
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
If you don't care about the timezone, you can just cut the timestamp out of that string:
const dateString = data.DateAdd;
const date = new Date(Number(dateString.match(/\d+/)[0]));
You can convert date into desired format by Javascript date object.
let addZero = (i) => {
if (i < 10) {
i = "0" + i;
}
return i;
}
let formatDate = (date) => {
let year = date.getFullYear(),
month = addZero(date.getMonth() + 1),
day = addZero(date.getDate() + 1),
hours = addZero(date.getHours() + 1),
minutes = addZero(date.getMinutes() + 1),
seconds = addZero(date.getSeconds() + 1);
let dateArr = [year, month, day];
let timeArr = [hours, minutes, seconds];
let result = dateArr.join('-').concat(" ", timeArr.join(':'));
return result;
}
let inputString = "/Date(1582936941390-0600)/";
let inputData = new Date(Number(inputString.match(/\d+/)[0]));
console.log(formatDate(inputData));
Please read more about Javascript date object
I am finding the best solution for extracting day, month, year from string with YYYY-DD-MM in Javascript:
Extract from:
2019-25-01
To object:
{ day: 25, month: 01, year: 2019 }
What is the best way to do it. Thank in advance!
You could split, destructure and return a new object.
const getDate = string => (([year, day, month]) => ({ day, month, year }))(string.split('-'));
console.log(getDate('2019-25-01'));
I'd use a regular expression to match each number sequence, map the array of matched strings to numbers, destructure into variables, then create an object from it:
const [year, day, month] = '2019-25-01'
.match(/\d+/g)
.map(Number);
const obj = { day, month, year };
console.log(obj);
Note that numbers cannot have leading zeros. If you want the month to have a leading zero, use a string instead (just remove the .map(Number)).
This is a pretty short and fast solution that will only work for that format and in ES6
function getJsonDate(text) {
var {0: year, 1: day, 2: month } = text.split("-");
return { day, month, year};
}
console.log(getJsonDate("2019-25-1"));
If you need the fields to be numbers then you can add a map, like so:
function toNumber(text) {
text = text - 0;
return isNaN(text) ? 0 : text;
}
function getJsonDate(text) {
var {0: year, 1: day, 2: month } = text.split("-").map(toNumber);
return { day, month, year};
}
console.log(getJsonDate("2019-25-1"));
You can split()to do it
var value = "2019-25-01";
var year = value.substring(0,4);
var day = value.substring(5,7);
var month = value.substring(8,10);
var str = "{day:" + day + ",month:" + month + ",year:" + year + "}";
console.log(str);
Use .split().
let date = "2019-25-01"
let dateArr = date.split('-')
let obj = {
day: dateArr[1],
month: dateArr[2],
year: dateArr[0]
}
console.log(obj)
For JSON like structure
d="2019-25-01";
x=d.split("-");
json="{ day: "+x[1]+", month: "+x[2]+", year: "+x[0]+" }";
>>"{ day: 25, month: 01, year: 2019 }"
Here you have one approach that don't need to do the mapping str -> array -> object, it will convert the string directly to object and can be used also for a more generalized date with time. It is based on the replacement function that can be used on String::replace()
const dateStr1 = "2019-25-01";
const dateMap1 = ["year", "day", "month"];
const dateStr2 = "2019-25-01 17:07:56";
const dateMap2 = ["year", "day", "month", "hour", "minute", "second"];
const splitDate = (str, map) =>
{
let obj = {}, i = 0;
str.replace(/\d+/g, (match) => obj[[map[i++] || i - 1]] = match);
return obj;
}
console.log(splitDate(dateStr1, dateMap1));
console.log(splitDate(dateStr2, dateMap2));
Another way that is strictly related to your date format could be next one:
const strDate = "2019-25-01";
const splitDate = (str) =>
{
let [date, year, day, month] = str.match(/(\d+)-(\d+)-(\d+)/);
return {year, month, day};
}
console.log(splitDate(strDate));
In Javascript I'm trying to convert a Date object to a locale string, with the toLocaleString() function. What I want is the converted locale string with milliseconds. Is that possible?
const time = "2018-12-03T16:24:05.150Z";
const date = new Date(time);
const str = date.toLocaleString();
console.log(date.toLocaleString()); //3-12-2018 17:24:05
the key is fractionalSecondDigits
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
//output: 2022-06-10 21:51:59,618 GMT−04:00
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
//output: 2022-06-10T21:51:59.618-04:00
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
What about using date.getMilliseconds() ?
const time = "2018-12-03T16:24:05.150Z";
const date = new Date(time);
const str = date.toLocaleString();
console.log(date.toLocaleString() + " " + date.getMilliseconds());
//3-12-2018 17:24:05 ???
const time = "2018-12-03T16:24:05.150Z";
const date = new Date(time);
const str = date.toLocaleString();
const result = new Date(str).getTime();
console.log(result);
As mentioned a keyword for milliseconds is missing.
I built a javascript clock for practise and run into the same problem but I already built an interface for toLocaleString so I decide to add my own feature that probably won't work with all languages but it's good enough.
I choose millisecond as keyword. I think as format information a combination of using n-digit like 2-digit and anything for no specific millisecond format (cause also include numeric) would be enough.
As connection I use colon when the format of hourCycle is defined as h23 or h24 and space else.
(Code in snippet without error handling, trigger is onchange so fill in en and than change hourCycle to h11)
function toLocalStringFromDate(nDate, nLanguage, nOptions){
if("millisecond" in nOptions){ // own keyword option
if(nOptions.millisecond.endsWith("-digit")){
let tDigits = parseInt(nOptions.millisecond.substring(0, nOptions.millisecond.length-6));
// extract amount of digits from format
let tLength = (""+nDate.getMilliseconds()).length;
// length of current milliseconds
return nDate.toLocaleString(nLanguage, nOptions)
// basic formatting
+("hourCycle" in nOptions && (nOptions.hourCycle == "h23" || nOptions.hourCycle == "h24") ? ':' : ' ')
// separator
+("0".repeat(tDigits)+nDate.getMilliseconds()).substring(tLength, tDigits+tLength);
// n-digit of zeros followed by milliseconds shifted by n digit is substring(tDigits+tLength-tDigits, tDigits+tLength);
}
else{
return nDate.toLocaleString(nLanguage, nOptions)+("hourCycle" in nOptions && (nOptions.hourCycle == "h23" || nOptions.hourCycle == "h24") ? ':' : ' ')+nDate.getMilliseconds();
}
}
else{
return nDate.toLocaleString(nLanguage, nOptions);
}
}
window.document.body.children[1].lastElementChild.value = "{\"hourCycle\": \"h23\", \"millisecond\": \"3-digit\"}";
input{width: 60%;}
<p><b>Language: </b><input onchange="console.log(toLocalStringFromDate(new Date(), this.value, JSON.parse(this.parentElement.nextElementSibling.lastElementChild.value)));"></p>
<p><b>Options: </b><input onchange="console.log(toLocalStringFromDate(new Date(), this.parentElement.previousElementSibling.lastElementChild.value, JSON.parse(this.value)));"></p>
You can achieve this with the following lines of code
const date = new Date();
const localDateTime = date.toLocaleString();
const currentDateObj = new Date(localDateTime);
const convertLocalDateTimeToMS = currentDateObj.getTime();
console.log(convertLocalDateTimeToMS); // 1630060060000
I am using slice()to take apart strings, but it does not work correctly.
strings:
var datept = "2018-01-19"
var timept = "12:05"
disjoint:
var month = datept.slice(5, -3); // should: "01" is: "01"
var day = datept.slice(8, -0); // should: "19" is: "" -- WRONG
var year = datept.slice(0, -6); // should: "2018" is: "2018"
var hours = timept.slice(0, -3); // should: "12" is: "12"
var minutes = timept.slice(3, -0); // should: "05" is: "" -- WRONG
also tried:
var day = datept.slice(-8, -0); // or
var day = datept.slice(8, -0); // or
var day = datept.slice(-8, 0); // or
var day = datept.slice(8, 0);
You could split the date and use a destructuring assignment for the values.
var datept = "2018-01-19",
timept = "12:05",
[year, month, day] = datept.split('-'),
[hours, minutes] = timept.split(':');
console.log(year, month, day);
console.log(hours, minutes);
Don't use -0. I'm not even sure what that's supposed to mean :) -0 is just 0, and slice will be confused by endIndex being lower than startIndex.
Here:
var day = datept.slice(8, -0); // should: "19" is: "" -- WRONG
Instead:
var day = datept.slice(8); // should: "19" is: "19"
Anyway, there's better ways of doing this. You could manipulate a Date object (though those are not exactly intuitive), or use split() to get the fragments instead:
> var parts = "2018-01-19".split("-")
> parts[0] // '2018'
> parts[1] // '01'
> parts[2] // '19'
Using modern javascript, you can even:
> const [ year, month, day ] = "2018-01-19".split("-")
> year // '2018'
> month // '01'
> day // '19'
Why not using string.split()?
let str = "2018-01-19";
let parts = str.split("-");
let day = parts[2];
let month = parts[1];
let year = parts[0];
This solution its simply stupid. Why won't you convert to a Date object (native) or even a use moment (you will have to import it) and then get what you want with the help of helper functions?
let c = new Date("2018-01-19")
c.getDate() // 19
c.getMonth() + 1 // 0 (its from 0-11)
and soo on. See more documentation for each on highlights.