How to convert format date to dd/mm - javascript

Heloo, i want to convert format date 2022-04-09 08:00:33 to format 9 April. i was trying to convert it, but the format still wrong, thanks for help me before
#solved

When it comes to date manipulation in JavaScript, there are a lot of third-party libraries available. Some of the most popular options are Moment.js and Day.js. When it comes to formatting a date into a custom format, these libraries are really easy to use.
Example:
moment('2022-04-09 08:00:33','YYYY-MM-DD HH:mm:ss').format('D MMMM')
converts:
2022-04-09 08:00:33 to 9 April
You can visit the link to see available formats.
Or You can use a simple solution that involves native date class:
const date = new Date().toLocaleDateString('en-gb', {
day: 'numeric',
month: 'long',
});
console.log(date)
but for this input date should be in proper date format i.e., ISO String of timestamp in milliseconds.
The arrangement of day and month will be according to locale you use.

export const formatDate = (date) => {
const newDate = new Date(date)
const month = newDate.toLocaleString('default', { month: 'long' })
const day = newDate.getDate()
const formated = `${day} ${month}`
return formated
}

Related

how to Convert Date into ISO Date Format in javascript

i have a date like this which i should convert them into ISO format
const date = 05/23/2022;
i need like this
2022-05-23T00:00:00Z
Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.
let date = '24.05.2022 0:00:00';
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
You can use String.split() to get the day, month and year for the Date in question.
We can then pass to the Date.UTC() function and then the Date() constructor. (Note: We pass monthIndex to the Date constructor, that's why we subtract 1 from the month )
To display as an ISO string, we can then use Date.toISOString()
const [month, day, year] = '05/23/2022'.split('/');
const date = new Date(Date.UTC(year, month - 1, day));
const result = date.toISOString();
console.log('Date (ISO):', result);
We can also do this easily with a Date / Time library such as luxon.
We'd use the DateTime.fromFormat() function to parse the input string, setting the timezone to 'UTC'.
To output the ISO date, we can use the DateTime.toISO() function:
const { DateTime } = luxon;
const date = DateTime.fromFormat('05/23/2022', 'MM/dd/yyyy', { zone: 'UTC'});
console.log('Date (ISO):', date.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
We can also do this in moment.js, using moment.utc(), then .toISOString():
const date = moment.utc('05/23/2022', 'MM/DD/YYYY');
console.log('Date (ISO):', date.toISOString())
<script src="https://momentjs.com/downloads/moment.js"></script>

How to generate date in the format of credit/debit card expiry date? [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 1 year ago.
I have a requirement of generating dates in this format 'Thru: 12/20' (like credit/debit card expiry date format). What is the best way of generating date in this format?
new Date().toJSON().slice(0,7).split('-').reverse().join('/')
I got the date in mm/yyyy format but couldn't get the desired result
You can use Intl.DateTimeFormat to generate date in day name and dd/MM format
const options = { weekday: 'short', month: 'numeric', day: 'numeric' };
const result = new Intl.DateTimeFormat('en-GB', options).format(new Date());
console.log(result);
With Moment you can simply do:
const date = moment().format("ddd DD/MM");
console.log("Valid until : " + date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Is there a function to get the UTC date in the Locale String Format?

I want to get the current UTC date in JavaScript, but display it in the local date format (like Date.toLocaleDateString() does).
I first tried to just get the current UTC Date with Date.toUTCString() but that doesn't actually print out in the local format.
I then tried using the options configuration in toLocaleDateString(), but that just printed the local date and not the UTC date in the local format.
e.g. new Date().toLocaleDateString(options = {timeZone: "UTC"})
I then tried formatting using Intl.DateTimeFormat(), but that just gives the same results as Date.toLocaleDateString() does.
If there was a way to get the locale format then I'd be happy to use that format to format the UTC Date, but as far as I can tell there is none.
For example, given the new Date("Sat, 30 Mar 2019 00:27:19 GMT"), In the US, I should print out "3/30/2019", in Europe I should print out "30/3/2019", and so on, for every supported locale.
However, new Date("Sat, 30 Mar 2019 00:27:19 GMT").toLocaleDateString(options = {timeZone: "UTC"}) will print out "3/29/2019" instead.
I also wanted to display a date using localized string settings, like toLocaleDateString() does, but using the date's UTC value, instead of the local time zone.
For example:
I do want the localized string format, but I also want the UTC value instead of the local time zone value. The desired output in this example would be 4/3/2019, instead of 4/2/2019.
I acknowledged #AndersonHappens suggestion, but I have not used it. Here is what I did, instead:
There is a getTimezoneOffset() function, which provides the local time zone offset.
We can use this function result and create a new Date, applying the diff. Then, we can use toLocaleDateString() directly, as usual, to get the date in localized string format:
The solution as a function could be like this:
function toLocaleUTCDateString(date, locales, options) {
const timeDiff = date.getTimezoneOffset() * 60000;
const adjustedDate = new Date(date.valueOf() + timeDiff);
return adjustedDate.toLocaleDateString(locales, options);
}
Given a date, you can get the locale format with new Intl.DateTimeFormat().
You can then use formatToParts in order to get the formatting of the date and each specific component.
Following the example in the formatToParts documentation, I created the following method to get the UTC date in the locale string.
function toLocaleUTCDateString(date) {
let formatter = new Intl.DateTimeFormat();
return formatter.formatToParts(date).map(({type, value}) => {
switch (type) {
case 'day': return date.getUTCDate();
case 'hour': return date.getUTCHours();
case 'minute': return date.getUTCMinutes();
case 'month': return date.getUTCMonth() + 1;
case 'second': return date.getUTCSeconds();
case 'timeZoneName': return "UTC";
case 'year': return date.getUTCFullYear();
default : return value;
}
}).reduce((string, part) => string + part);
}
Do note however that this method does not remember number versus string formatting. For example, if you want to display the month of March as "March" (or the specific language month string), and not as the number 3, you would have to figure out how to do that yourself. It also doesn't handle discrepancies in weekdays, so if the local date is "Friday" and the UTC Date is "Saturday", you would have to figure that out separately as well.
You almost got it right - the timeZone option is available in the second argument. The first argument to toLocaleDateString is for the locales.
This example from your question works when options are the second argument (and is much simpler than other answers):
const usLocale = 'en-US'
new Date('Sat, 30 Mar 2019 00:27:19 GMT').toLocaleDateString(usLocale, {
timeZone: 'UTC',
})
// '3/30/2019'
const ukLocale = 'en-GB'
new Date('Sat, 30 Mar 2019 00:27:19 GMT').toLocaleDateString(ukLocale, {
timeZone: 'UTC',
})
// '30/03/2019'
var dateToPrint = new Date(Date.UTC(2020, 3, 23, 15, 0, 0));
new Date(
dateToPrint.getUTCFullYear(),
dateToPrint.getUTCMonth(),
dateToPrint.getUTCDate(),
dateToPrint.getUTCHours(),
dateToPrint.getUTCMinutes(),
dateToPrint.getUTCSeconds()
).toLocaleString('es-ES')
see image
Inside the toLocaleDateString you can pass options. There is an option name TimeZone. You have to set it to 'UTC'
const dateToParse = new Date()
dateToParse.toLocaleDateString(locate, { timeZone: 'UTC' })
Check out Intl.DateTimeFormat on MDN!
Using it is as simple as
// do this once in a central library file
const formatter = new Intl.DateTimeFormat('en', {
timeZone: 'UTC',
timeZoneName: 'short',
month: 'short',
day: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit',
})
// reuse anywhere for consistency
const myDate = new Date(
'Thu Feb 10 2022 12:50:14 GMT+0100'
)
formatter.format(myDate) === 'Feb 10, 11:50 UTC' // true
Open your console, copy-paste the code and start playing!
Again, Intl.DateTimeFormat on MDN.
Enjoy!
toLocaleString receives some parameters, the first parameter is the locale. To solve your issue specifically, you need to understand that UTC is not a locale. What you could to to accomplish what you want is to pass either 'en-US' for 3/29/2019 and 'en-GB' for 29/03/2019 hope that helps!

How to convert a full date to a short date in javascript?

I have a date like this Monday, January 9, 2010
I now want to convert it to
1/9/2010 mm/dd/yyyy
I tried to do this
var startDate = "Monday, January 9, 2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "/" + day + "/" + year;
However it must be thinking the date is in a different format since day returns 1 instead of 9.
Here you go:
(new Date()).toLocaleDateString('en-US');
That's it !!
you can use it on any date object
let's say.. you have an object called "currentDate"
var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy
(or)
If you want it in local format then
currentDate.toLocaleDateString(); // gives date in local Format
The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:
var day = convertedStartDate.getDate();
If you like, you can try to add a custom format function to the prototype of the Date object:
Date.prototype.formatMMDDYYYY = function(){
return (this.getMonth() + 1) +
"/" + this.getDate() +
"/" + this.getFullYear();
}
After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)
(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11
It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)
Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:
new Date(dateString).toLocaleDateString('en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
Alternative: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:
const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
document.getElementById("demo").innerHTML = d.toLocaleDateString();
date.toLocaleDateString('en-US') works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
I wanted the date to be shown in the type='time' field.
The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.
Hence I added a small statement (check)?(true):(false) as follows:
makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}
Although this question posted long long time ago, the proper way to do this is:
Intl.DateTimeFormat("en").format(new Date())
Any way, the Intl (international) object has many options you can pass to like to enforce tow digits etc.
You all can look at it here
I was able to do that with :
var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))
the 04/04/2013 is just for testing, replace with your Date Object.
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
Try this:
new Date().toLocaleFormat("%x");

Display date/time in user's locale format and time offset

I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
Bonus if I can output in the user's locale date format.
Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.
Then the various toLocale…String methods will provide localized output.
Example:
// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString()); // -> 02/28/2004
console.log(d.toLocaleTimeString()); // -> 23:45:26
Some references:
toLocaleString
toLocaleDateString
toLocaleTimeString
getTimezoneOffset
You can do it with moment.js (deprecated in 2021)
It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):
var m = moment("2013-02-08T09:30:26Z");
Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.
You can even format a moment object in the users locale like this:
m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us
To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.
Note: Moment JS recommends more modern alternatives, so it is probably not a good choice for new projects.
You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.
Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.
var d = new Date();
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0, 10);
// 2017-05-09T08:24:26.581Z (but this is not UTC)
The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.
2021 - you can use the browser native Intl.DateTimeFormat
const utcDate = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat().format(utcDate));
// expected output: "21/04/2021", my locale is Switzerland
Below is straight from the documentation:
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat('en-US').format(date));
// expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));
// Expected output "Sunday, 20 December 2020 at 14:23:16 GMT+11"
Once you have your date object constructed, here's a snippet for the conversion:
The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.
function UTCToLocalTimeString(d, format) {
if (timeOffsetInHours == null) {
timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
}
d.setHours(d.getHours() + timeOffsetInHours);
return d.strftime(format);
}
// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server
var serverDateStr = serverDate.toLocaleString("en-US", {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
})
var userDate = new Date(serverDateStr + " UTC");
var locale = window.navigator.userLanguage || window.navigator.language;
var clientDateStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric'
});
var clientDateTimeStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log("Server UTC date: " + serverDateStr);
console.log("User's local date: " + clientDateStr);
console.log("User's local date&time: " + clientDateTimeStr);
Here's what I've used in past projects:
var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');
The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)
To the get a normal time-zone offset in hours, you need to use:
var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60
Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.
With date from PHP code I used something like this..
function getLocalDate(php_date) {
var dt = new Date(php_date);
var minutes = dt.getTimezoneOffset();
dt = new Date(dt.getTime() + minutes*60000);
return dt;
}
We can call it like this
var localdateObj = getLocalDate('2015-09-25T02:57:46');
I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.
The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z
Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.
Python/Django: send request browser language as context parameter:
language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })
HTML: write it in a hidden input:
<input type="hidden" id="browserlanguage" value={{ language }}/>
JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression
const browserlanguage = document.getElementById("browserlanguage").value;
var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1");
JavaScript: convert to datetime and format it:
var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The result is (browser language is en-gb): 05/12/2016, 14:58
The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.
http://momentjs.com/ Moment.js
will display the time nicely.
You could use the following, which reports the timezone offset from GMT in minutes:
new Date().getTimezoneOffset();
Note :
- this function return a negative number.
getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.
There's a few more options discussed in the answer to this question
To convert date to local date use toLocaleDateString() method.
var date = (new Date(str)).toLocaleDateString(defaultlang, options);
To convert time to local time use toLocaleTimeString() method.
var time = (new Date(str)).toLocaleTimeString(defaultlang, options);
A very old question but perhaps this helps someone stumbling into this.
Below code formats an ISO8601 date string in a human-friendly format corresponding the user's time-zone and locale. Adapt as needed. For example: for your app, are the hours, minutes, seconds even significant to display to the user for dates more than 1 days, 1 week, 1 month, 1 year or whatever old?
Also depending on your application's implementation, don't forget to re-render periodically.
(In my code below at least every 24hours).
export const humanFriendlyDateStr = (iso8601) => {
// Examples (using Node.js):
// Get an ISO8601 date string using Date()
// > new Date()
// 2022-04-08T22:05:18.595Z
// If it was earlier today, just show the time:
// > humanFriendlyDateStr('2022-04-08T22:05:18.595Z')
// '3:05 PM'
// If it was during the past week, add the day:
// > humanFriendlyDateStr('2022-04-07T22:05:18.595Z')
// 'Thu 3:05 PM'
// If it was more than a week ago, add the date
// > humanFriendlyDateStr('2022-03-07T22:05:18.595Z')
// '3/7, 2:05 PM'
// If it was more than a year ago add the year
// > humanFriendlyDateStr('2021-03-07T22:05:18.595Z')
// '3/7/2021, 2:05 PM'
// If it's sometime in the future return the full date+time:
// > humanFriendlyDateStr('2023-03-07T22:05:18.595Z')
// '3/7/2023, 2:05 PM'
const datetime = new Date(Date.parse(iso8601))
const now = new Date()
const ageInDays = (now - datetime) / 86400000
let str
// more than 1 year old?
if (ageInDays > 365) {
str = datetime.toLocaleDateString([], {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
// more than 1 week old?
} else if (ageInDays > 7) {
str = datetime.toLocaleDateString([], {
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
// more than 1 day old?
} else if (ageInDays > 1) {
str = datetime.toLocaleDateString([], {
weekday: 'short',
hour: 'numeric',
minute: 'numeric',
})
// some time today?
} else if (ageInDays > 0) {
str = datetime.toLocaleTimeString([], {
timeStyle: 'short',
})
// in the future?
} else {
str = datetime.toLocaleDateString([], {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
}
return str
}
Inspired from: https://alexwlchan.net/2020/05/human-friendly-dates-in-javascript/
Tested using Node.js
Don't know how to do locale, but javascript is a client side technology.
usersLocalTime = new Date();
will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.

Categories