[Dataviewjs] Get an automatic humanized, "Morning", "Afternoon", "Evening". **Great for user greetings!

You don’t need to do anything, it’s automatic. The code will directly by your system write your greeting according to your local time with a time-aware.

You can edit the greeting there to suit your needs or even add your name after it.

Personally I’m using this for my Daily Note, but you can use it for your homepage or anythings you want.

I’m sharing this because I think it’s nice to have a welcome message in our homepage :).

Copy

```dataviewjs
const currentHour = moment().format('HH');
console.log(currentHour)
let greeting;
if (currentHour >= 18 || currentHour < 5) {
greeting = '🌙 Good Evening'
} else if (currentHour >= 5 && currentHour < 12) {
greeting = '🌞 Good Morning'
} else {
greeting = '🌞 Good Afternoon'
}
dv.header(2, greeting)
```
12 Likes

I love this! Thanks for posting it.

Just for fun, I added a small random element to it:


let morning = [
    "Let's do great work today!",
    "It's a new day!"
];

let afternoon = [
    "Let's finish the day well!",
    "Let's keep up our focus!",
    "Need another cup of coffee? ☕"
];

let evening = [
    "Time to go home!",
    "Your family misses you!"
];

const currentHour = moment().format('HH'); 
let greeting; 

if (currentHour >= 17 || currentHour < 5) { 
    greeting = "🌙 Good Evening! "
        + evening[Math.floor(Math.random()*evening.length)];
} else if (currentHour >= 5 && currentHour < 12) { 
    greeting = "🌞 Good Morning! " +
        + morning[Math.floor(Math.random()*morning.length)];
} else { 
    greeting = "🌞 Good Afternoon! "
        + afternoon[Math.floor(Math.random()*afternoon.length)];
} 
dv.paragraph(greeting);
7 Likes

Thanks for this, I love the addition of an element of randomness! Is there any way to get Dataview to return a random greeting from an inline field, i.e. if I were to add evening:: Take a deep breath or morning:: Pour another cup to some of my daily note pages, could this snippet be modified to pull a sample from one of those?

Really, I’ve been trying to get a daily gratitude reminder, but I keep banging my head against the limitations of my scripting knowledge.

Sure, you can pull every instance of a field from all your pages. It requires a little more code to do it. Here’s code that pulls the value of every page that has a “message” field into an array called “messages”:

```dataviewjs
// List of messages
let messages = [];

// Extract messages from pages that have them
dv.pages()
	.where(page => page.message)
	.forEach(page => {
		dv.array(page.message).forEach(message => {
			messages.push(message); })});

let greeting = messages[Math.floor(Math.random()*messages.length)]

dv.paragraph(greeting);
```
3 Likes

That’s lovely, and works perfectly for my purposes—thank you so much!

1 Like